Most of the websites are using Java script to enrich the webpage i.e.;

  • To have a better UI components like date calendar control
  • To validate the data entered by users
  • To enable share pod

It is obvious that the performance will go down if you load more number of Java script files. So, we've to be very careful while including new Java script code on the webpage. One of the options is to load the Java script only when it is needed. This concept is called "Lazy loading".

I'm going to explain you how you can implement the lazy loading of Java script. It's very simple. Implement this in 3 easy steps.

  • Include the code below on your page
  • Call loadJSFile function with the Java script URL/path
  • Implement the code that should be run just after the JS file rednered in the callBack() function
function loadJSFile(src)
{
  var scriptElement = document.createElement("script");
  scriptElement.setAttribute("type", "text/javascript");
  scriptElement.setAttribute("src", src);
  // Handled for IE 6 & 7
  if(navigator.userAgent.indexOf('MSIE')>=0){
    scriptElement.onreadystatechange = function(){
      if (this.readyState == 'loaded' || this.readyState == 'complete'){
        callBack();
      }
    }
  }else{
    //For other browsers
    scriptElement.onload = callBack;
  }
  if(typeof scriptElement != "undefined"){
    document.getElementsByTagName("head")[0].appendChild(scriptElement);
  }
}
//Call back function
function callBack()
{
  sayHello(); //Code that you want to invoke just after the JS file rendered
}

Interested to see it on live - Live demo