user2269215
user2269215

Reputation: 272

is js blocking for page render or not?

i read about "critical rendering path" and js is show as blocking but my experience is little different.

critical rendering path picture http://i59.tinypic.com/29qnq88.jpg

1, if i put external javascript to head and reload page i see blank page until script is loaded parsed and so on. (this is exactly in picture)

2, if i put the same javascript before end of body element, i see rendered page and script is still loading from server.

why is different put the same external js in head and in body? critical rendering path isnt the same?

Upvotes: 0

Views: 122

Answers (2)

earroyoron
earroyoron

Reputation: 192

As javascript can change both DOM and CSSOM, it stop any CRP phase and is blocking,... unless is async!

Upvotes: 0

Pointy
Pointy

Reputation: 414036

The <script> blocks are evaluated as the HTML parser encounters them in the document. When a <script> block is at the end of the <body>, the parser has most of the DOM already built and can begin to render it to the screen. (It may still be waiting for images or fonts, so the layout may change, but it can get started.)

When the <script> is in the head, however, the browser has no idea what's in the document body, so there's nothing to render.

Understanding this, I guess, requires that you have at least a basic idea of what's going on when the browser receives the contents of an HTML page. The page contents are "digested" element by element, and that's done recursively. The contents of container elements are processed from top to bottom.

During that process, when a <script> tag is seen completely (that is, the browser has consumed the portion of the HTML contents from the opening <script> to the closing </script>) then the JavaScript code is evaluated before the parsing process moves on to the remainder of the page contents. (I'm ignoring here the new-ish optional "async" attribute on <script> tags.)

Upvotes: 3

Related Questions