How to load JavaScript without blocking

In this example we will show a few methods of loading javascript without blocking the page load.

  1. XHR Eval
  2. XHR Injection
  3. Script DOM Element
  4. Script Defer
  5. document.write Script Tag

XHR Eval

This uses an XMLHttpRequest (XHR) to get the JavaScript, which is then executed using the eval

var xhrObj = getXHRObject();
xhrObj.onreadystatechange = 
  function() { 
    if ( xhrObj.readyState == 4 && 200 == xhrObj.status ) 
    {
      eval(xhrObj.responseText);
    }
  };
xhrObj.open('GET', 'myScript.js', true);
xhrObj.send('');

XHR Injection

This uses an XMLHttpRequest (XHR) to get the JavaScript, which is then executed by injecting it into a script tag which is dynamically created

var xhrObj = getXHRObject();
xhrObj.onreadystatechange = 
  function() { 
    if ( xhrObj.readyState == 4 )
    {
      var scriptElement = document.createElement('script');
      document.getElementsByTagName('head')[0].appendChild(scriptElement);
      scriptElement.text = xhrObj.responseText;
    }
  };
xhrObj.open('GET', 'myScript.js', true);
xhrObj.send('');

Script DOM Element

This uses JavaScript to create a script element and set the src property

var scriptElement = document.createElement('script');
scriptElement.src = 'http://example.com/myScript.js';
document.getElementsByTagName('head')
[0].appendChild(scriptElement);

Script Defer

This uses the defer property of the script tag, this is supported by Internet Explorer. It tells the browser not to load the script immediately


document.write Script Tag

This uses the document.write method to put the script tag into the page

document.write("");

Both XHR Eval and XHR Injection use this method, but it might be simpler to use JQuery.ajax but that would mean that the JQuery library would have to load first

function getXhrObject() {
        if (window.XMLHttpRequest)
                return new XMLHttpRequest();
        if (window.ActiveXObject) {
                var names = [ "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.3.0","Msxml2.XMLHTTP", "Microsoft.XMLHTTP" ];
                for (var i in names) {
                        try{
                                return new ActiveXObject(names[i]);
                        }catch (e){
                                //Nothing
                        }
                }
        }
        return null;
}


Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.