Thursday, July 11, 2013

Fine Tune JavaScript - On Demand Script loading

Dynamically loading external scripts is one of the techniques used to write non-blocking JavaScript code.  It is a three step process –

  • Create an element for the <script> tag.
  • Set the source of the <script> element as the location of the external script file.
  • Append the <script> element to either of the two - <body> or <head>, tag.

In this example, we try to load the external script dynamically –

  var scriptObj = document.createElement('script');
  scriptObj.src = 'external-script.js';
  document.getElementsByTagName("head")[0].appendChild(scriptObj);


This new <script> element loads the source file external-script.js. The file begins downloading as soon as the element is added to the page. The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated.  

You can also attach event handlers to take action when the script is downloaded completely. But there is slight different between the event which is being fired in case of IE and rest of the browsers (Firefox, Opera, Chrome, Safari ). Firefox, Opera, Chrome, and Safari 3+ all fire a load event when the src of a
<script> element has been retrieved. In case of IE, readystatechange event is triggered.

This example takes care of both the use-case –

        var script = document.createElement("script")
        script.type = "text/javascript";
        
        //Internet Explorer
        if (script.readyState){
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" || script.readyState == "complete"){
                    script.onreadystatechange = null;
                    alert("Script loaded.");
                }
            };

        } else{
            //Firefox, Opera, Chrome, Safari 3+
            script.onload = function(){
                alert("Script loaded!");
            };

        }
        script.src = "file1.js";
        document.getElementsByTagName("head")[0].appendChild(script);

 


 


No comments: