Saturday, August 8, 2015

Load external JS file in non-blocking mode

Loading external JavaScript file in blocking mode could cause bottleneck of application’s performance. Normal behavior of Browser is to wait until all JS file load the reason is, any JS code in any file may change the design or content.

Anyway, there is couple of ways to load external JS file asynchronously or non-blocking way. In this article, we will discuss on by one of them.
Using “defer”

defer attribute makes promise to browser. When we are using defer and browser consider this attribute as expected, we should not include any DOM processing JS file in this. The reason is browser will not wait until the file load.
The syntax is like this.

<script src="~/js/js1.js" defer></script>

When browser encounter “defer” it consider the script as parallel loadable object. Now , the question is when defer code will execute ?

In theory, it should happen after the DOM has completely loaded, shortly before the DOMContentLoaded event. In practice, it depends on the OS and browser, whether the script is cached, and what other scripts are doing at the time.
Using “async”

This attribute has introduced in HTML5. async is identical to defer, except that the script executes at the first opportunity after download (an optional onload attribute can be added to run a specific function). You can’t guarantee that scripts will execute in sequence, but they will have loaded by the time the window onload event fires.There’s support for async in Firefox 3.6, Opera 10.5, and the latest WebKit build, so it should appear in the next versions of Chrome and Safari. IE9 is yet to support async, but the IE team could easily add it as an alias for defer. You can use both async and defer to support all browsers — even IE4.Perhaps within a few months, we’ll finally have a native, non-blocking JavaScript loading method that works in all browsers.
Let us see the loading sequence of async. In this example we are loading four external JS files and the sequence is like this.




Please note than “Raphael-min.js” is loading asynchronously.  Here is screen of loading in reality.


We are seeing that “Raphael-min.js” is loading in second position but in sequence, it is in third position. Again, this sequence of loading for some trial, it may vary time to time.


No comments:

Post a Comment