Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do inline scripts block rendering when put at the bottom of a page?

I read High Performance Web Sites: Essential Knowledge for Front-End Engineers and in it the author suggests that all JavaScript code should be externalized and put at the bottom of the page instead of putting it in the head.

This is illustrated in this example. The external script tag blocks both downloading and progressive rendering of a page, so the solution was to put it at the bottom of the page.

However, in his second book Even Faster Web Sites: Performance Best Practices for Web Developers he talks about Inline JavaScript tags.

Inline scripts also blocks downloading and rendering of a page, so he suggests moving them also to the bottom of the page. However, this acts still blocks the rendering of the page entirely as illustrated in this example

Why do moving external scripts to the bottom of the page lets the page render progressively while moving inline scripts blocks rendering completely till the script is executed?


PS:

The question isn't about why add JavaScript to the bottom of the page instead of putting them in the head. It's about why bottom inline scripts block rendering while bottom external scripts don't.

like image 511
Songo Avatar asked Aug 17 '13 20:08

Songo


People also ask

Do inline scripts block rendering of a page?

Inline scripts block the rendering of everything in the page. You can see this by loading the Inline Scripts Block example in a new window and count off the five seconds before anything is displayed.

What is render-blocking?

Render-blocking resources are portions of code in website files, usually CSS and JavaScript, that prevent a web page from loading quickly. These resources take a relatively long time for the browser to process, but may not be necessary for the immediate user experience.

Where do you put an inline script?

Inline JavaScript can be achieved by using Script tag inside the body of the HTML, and instead of specifying the source(src=”…”) of the JavaScript file in the Script tag, we have to write all the JavaScript code inside the Script tag.

Are images render-blocking?

No, images are not render-blocking. It's still important to optimize your images to reduce their file sizes, but you do not need to worry about optimizing the delivery path for your images.


1 Answers

In the inline script, the time is taken up running the script, which might change the DOM. Trying to render the DOM while it's mutating is a recipe for a mess. So rendering only happens at points when the JS is stalled, and therefore the DOM is stable.

While waiting for an external script to download, the running of scripts is stalled, so the DOM can be rendered safely. The downloaded JS won't be run until the rendering is complete.

like image 133
Alohci Avatar answered Sep 22 '22 16:09

Alohci