Wednesday, 2 May 2012

JavaScript: asynchronous loading

   


JavaScript is an important part of web developing. We heavily rely on JavaScript library and more than often we use external reference to load js snippets. In order to link an external js file we usually insert the following code where needed:
<script src="http://externalDomain.com/script.js"></script>
If the externalDomain is someway busy or down, our page will hang, waiting for the externalDomain. The page will eventually be loaded and displayed when the resource becomes free. Worst case scenario: the externalDomain stays busy and our page stays completely blank.
There's a solution to the above issue: using asynchronous loading and here I show you how to use it.

Some background
With asynchronous loading, your external resource will be loaded only after the loading of the page. So, we should be careful in using it, because we have to be sure that the whole page is not totally relying on that external snippet.
On the good side of things, our page will load faster and it will be always ready for the user.

The code
The code is just a few lines:
<script type="text/javascript">
(function() {
    var asynScript = document.createElement('script');
    asynScript.type = 'text/javascript';
    asynScript.async = true;
    asynScript.src = 'http://externalDomain.com/script.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(asynScript , x);
})();
</script>
When our page is loaded the function is inserting the external resource in async mode. Infact we set the HTML5 attribute async to true.

The effect
As said above, the page will load faster, but we might end up dealing with some minor effects. For example, the asynchronous loading of the external resource could move page elements after the page is loaded, causing an unwanted "resetting" of some elements (like the sliding of a container). In other cases, some functions might be available to the user with a small delay, giving the impression that the page froze for a moment.
Those counter-effects can be solved by carefully placing the loaded content ('http://externalDomain.com/script.js') in the right spot or, for example, creating the needed space when the page loads.
In the end, we have to play with it a bit to fully understand how to correctly implement the asynchronous loading of JavaScript snippets. As usual, we need to test and trial, but I'm sure you will find the idea quite interesting in many cases.


2 comments:

  1. I recently published a standard for all the front end developers as a MUST follow - http://iskeleton.blogspot.in

    ReplyDelete
    Replies
    1. Thanks Dilip for sharing your work. I'm sure many TWT readers will find it interesting...

      Delete

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.