Home » Tutorials » JavaScript » How Quickly Can Async Scripts Improve Rendering Speed?

How Quickly Can Async Scripts Improve Rendering Speed?

How Quickly Can Async Scripts Improve Rendering Speed?

As we all know that, browser can only renders a page after it has build the DOM (Document Object Models) tree by parsing the HTML markup. During the process, whenever the parser encounters a <script> tag, it has to stop & being forced to wait for the JavaScript to be executed or even worse for external scripts that must be fetched before they can be executed. This was cause serious delay time to the first render of the page.

Instead of forcing parser to wait for a JavaScript to finish downloading before the page renders, we can actually add the HTML async attribute on external JavaScript to allow external scripts can be downloaded in the background. But, how quickly actually can Asynchronous JavaScripts improve the time of first render? Have you conducted any analysis on this topic before? If you haven’t already done so, let’s find out the answer today!

Before using HTML async attribute

Let’s say you have a web page with 9 external JavaScripts. Load the page in your Google Chrome, inspect it with the network waterfall panel tool & see what happened:

Before adding Async Script

**Click the image to enlarge it

Because we haven’t using HTML async attribute for loading external scripts, the domContentLoaded event is blocked  until all the JavaScripts file being downloaded & executed. So as you can see that the domContentLoaded (blue vertical line) is fires at 624s, and the onload event times is fires at 1.00s.

What if we add async attribute to 8 out of 9 external JavaScripts to shorten the time of blocking? * (I will exaplain why we didn’t add async attribute to all external scripts later).

Using HTML async to unblock external scripts

After Added Sync to JS

**Click to view large image of using HTML async to unblock external scripts

It’s about 35% faster than the previous! The domContentLoaded event fires shortly after the HTML file is parsed & the jQuery core library is loaded. As we can see the blue vertical line from the waterfall, the parser doesn’t need to wait for the rest of the external scripts loaded. Sounds great right? But, why we didn’t add async attribute to jQuery core library for this case? Well.. the main reason is asynchronous scripts are not guaranteed to execute in specified order and should not use document.write. Scripts that depend on execution order, due to these issue we should make sure that jQuery core library is loaded prior to any jQuery dependent plugins.

Conclusion

Adding async attribute to external JavaScript to unblock the parser, can dramatically reduce the time for about 35% of first render of the page.


Android, iOS Development Tutorials