load scripts asynchronously





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







114















I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because it takes some time to load. it will be nice if I can display the loader before importing all the:



<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/myFunctions.js"></script>
<link type="text/css" href="css/main.css" rel="stylesheet" />
...
....
etc


I have found several tutorials that enable me to import a JavaScript library asynchronously. for example I can do something like:



  (function () {
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = 'js/jquery-ui-1.8.16.custom.min.js';
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
})();


for some reason when I do the same thing for all my files the pages does not work. I have been trying for so long to try to find where the problem is but I just cannot find it. First I thought that it was probably because some javascript functions depended on the others. but I loaded them in the right order using the time out function when one completed I proceeded with the next and the page still behaves weird. for example I am not able to click on links etc... animations still work though..



Anyways



Here is what I have been thinking... I believe browsers have a cache that's why it takes a long time to load the page for the first time and the next time it is quick. so what I am thinking of doing is replacing my index.html page with a page that loads all this files asynchronously. when ajax is done loading all those files redirect to the page that I plan on using. when using that page it should not take long to load since the files should alredy be included on the cache of the browser. on my index page (page where .js and .css file get loaded asynchronously) I don't care of getting errors. I will just be displaying a loader and redirecting the page when done...



Is this idea a good alternative? or should I keep trying on implementing the asynchronously methods?





EDIT



the way I load everything async is like:



importScripts();

function importScripts()
{
//import: jquery-ui-1.8.16.custom.min.js
getContent("js/jquery-1.6.2.min.js",function (code) {
var s = document.createElement('script');
s.type = 'text/javascript';
//s.async = true;
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext1,1);
});


//import: jquery-ui-1.8.16.custom.min.js
function insertNext1()
{
getContent("js/jquery-ui-1.8.16.custom.min.js",function (code) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext2,1);
});
}

//import: jquery-ui-1.8.16.custom.css
function insertNext2()
{

getContent("css/custom-theme/jquery-ui-1.8.16.custom.css",function (code) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel ="stylesheet";
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext3,1);
});
}

//import: main.css
function insertNext3()
{

getContent("css/main.css",function (code) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel ="stylesheet";
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext4,1);
});
}

//import: jquery.imgpreload.min.js
function insertNext4()
{
getContent("js/farinspace/jquery.imgpreload.min.js",function (code) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext5,1);
});
}


//import: marquee.js
function insertNext5()
{
getContent("js/marquee.js",function (code) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext6,1);
});
}


//import: marquee.css
function insertNext6()
{

getContent("css/marquee.css",function (code) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel ="stylesheet";
s.innerHTML=code;
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
setTimeout(insertNext,1);
});
}



function insertNext()
{
setTimeout(pageReadyMan,10);
}
}


// get the content of url and pass that content to specified function
function getContent( url, callBackFunction )
{
// attempt to create the XMLHttpRequest and make the request
try
{
var asyncRequest; // variable to hold XMLHttpRequest object
asyncRequest = new XMLHttpRequest(); // create request object

// register event handler
asyncRequest.onreadystatechange = function(){
stateChange(asyncRequest, callBackFunction);
}
asyncRequest.open( 'GET', url, true ); // prepare the request
asyncRequest.send( null ); // send the request
} // end try
catch ( exception )
{
alert( 'Request failed.' );
} // end catch
} // end function getContent

// call function whith content when ready
function stateChange(asyncRequest, callBackFunction)
{
if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
{
callBackFunction(asyncRequest.responseText);
} // end if
} // end function stateChange


and the weird part is that all the style's work plus all the javascript functions. the page is frozen for some reason though...










share|improve this question































    114















    I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because it takes some time to load. it will be nice if I can display the loader before importing all the:



    <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
    <script type="text/javascript" src="js/myFunctions.js"></script>
    <link type="text/css" href="css/main.css" rel="stylesheet" />
    ...
    ....
    etc


    I have found several tutorials that enable me to import a JavaScript library asynchronously. for example I can do something like:



      (function () {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'js/jquery-ui-1.8.16.custom.min.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    })();


    for some reason when I do the same thing for all my files the pages does not work. I have been trying for so long to try to find where the problem is but I just cannot find it. First I thought that it was probably because some javascript functions depended on the others. but I loaded them in the right order using the time out function when one completed I proceeded with the next and the page still behaves weird. for example I am not able to click on links etc... animations still work though..



    Anyways



    Here is what I have been thinking... I believe browsers have a cache that's why it takes a long time to load the page for the first time and the next time it is quick. so what I am thinking of doing is replacing my index.html page with a page that loads all this files asynchronously. when ajax is done loading all those files redirect to the page that I plan on using. when using that page it should not take long to load since the files should alredy be included on the cache of the browser. on my index page (page where .js and .css file get loaded asynchronously) I don't care of getting errors. I will just be displaying a loader and redirecting the page when done...



    Is this idea a good alternative? or should I keep trying on implementing the asynchronously methods?





    EDIT



    the way I load everything async is like:



    importScripts();

    function importScripts()
    {
    //import: jquery-ui-1.8.16.custom.min.js
    getContent("js/jquery-1.6.2.min.js",function (code) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    //s.async = true;
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext1,1);
    });


    //import: jquery-ui-1.8.16.custom.min.js
    function insertNext1()
    {
    getContent("js/jquery-ui-1.8.16.custom.min.js",function (code) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext2,1);
    });
    }

    //import: jquery-ui-1.8.16.custom.css
    function insertNext2()
    {

    getContent("css/custom-theme/jquery-ui-1.8.16.custom.css",function (code) {
    var s = document.createElement('link');
    s.type = 'text/css';
    s.rel ="stylesheet";
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext3,1);
    });
    }

    //import: main.css
    function insertNext3()
    {

    getContent("css/main.css",function (code) {
    var s = document.createElement('link');
    s.type = 'text/css';
    s.rel ="stylesheet";
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext4,1);
    });
    }

    //import: jquery.imgpreload.min.js
    function insertNext4()
    {
    getContent("js/farinspace/jquery.imgpreload.min.js",function (code) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext5,1);
    });
    }


    //import: marquee.js
    function insertNext5()
    {
    getContent("js/marquee.js",function (code) {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext6,1);
    });
    }


    //import: marquee.css
    function insertNext6()
    {

    getContent("css/marquee.css",function (code) {
    var s = document.createElement('link');
    s.type = 'text/css';
    s.rel ="stylesheet";
    s.innerHTML=code;
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
    setTimeout(insertNext,1);
    });
    }



    function insertNext()
    {
    setTimeout(pageReadyMan,10);
    }
    }


    // get the content of url and pass that content to specified function
    function getContent( url, callBackFunction )
    {
    // attempt to create the XMLHttpRequest and make the request
    try
    {
    var asyncRequest; // variable to hold XMLHttpRequest object
    asyncRequest = new XMLHttpRequest(); // create request object

    // register event handler
    asyncRequest.onreadystatechange = function(){
    stateChange(asyncRequest, callBackFunction);
    }
    asyncRequest.open( 'GET', url, true ); // prepare the request
    asyncRequest.send( null ); // send the request
    } // end try
    catch ( exception )
    {
    alert( 'Request failed.' );
    } // end catch
    } // end function getContent

    // call function whith content when ready
    function stateChange(asyncRequest, callBackFunction)
    {
    if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
    {
    callBackFunction(asyncRequest.responseText);
    } // end if
    } // end function stateChange


    and the weird part is that all the style's work plus all the javascript functions. the page is frozen for some reason though...










    share|improve this question



























      114












      114








      114


      57






      I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because it takes some time to load. it will be nice if I can display the loader before importing all the:



      <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
      <script type="text/javascript" src="js/myFunctions.js"></script>
      <link type="text/css" href="css/main.css" rel="stylesheet" />
      ...
      ....
      etc


      I have found several tutorials that enable me to import a JavaScript library asynchronously. for example I can do something like:



        (function () {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.async = true;
      s.src = 'js/jquery-ui-1.8.16.custom.min.js';
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      })();


      for some reason when I do the same thing for all my files the pages does not work. I have been trying for so long to try to find where the problem is but I just cannot find it. First I thought that it was probably because some javascript functions depended on the others. but I loaded them in the right order using the time out function when one completed I proceeded with the next and the page still behaves weird. for example I am not able to click on links etc... animations still work though..



      Anyways



      Here is what I have been thinking... I believe browsers have a cache that's why it takes a long time to load the page for the first time and the next time it is quick. so what I am thinking of doing is replacing my index.html page with a page that loads all this files asynchronously. when ajax is done loading all those files redirect to the page that I plan on using. when using that page it should not take long to load since the files should alredy be included on the cache of the browser. on my index page (page where .js and .css file get loaded asynchronously) I don't care of getting errors. I will just be displaying a loader and redirecting the page when done...



      Is this idea a good alternative? or should I keep trying on implementing the asynchronously methods?





      EDIT



      the way I load everything async is like:



      importScripts();

      function importScripts()
      {
      //import: jquery-ui-1.8.16.custom.min.js
      getContent("js/jquery-1.6.2.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      //s.async = true;
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext1,1);
      });


      //import: jquery-ui-1.8.16.custom.min.js
      function insertNext1()
      {
      getContent("js/jquery-ui-1.8.16.custom.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext2,1);
      });
      }

      //import: jquery-ui-1.8.16.custom.css
      function insertNext2()
      {

      getContent("css/custom-theme/jquery-ui-1.8.16.custom.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext3,1);
      });
      }

      //import: main.css
      function insertNext3()
      {

      getContent("css/main.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext4,1);
      });
      }

      //import: jquery.imgpreload.min.js
      function insertNext4()
      {
      getContent("js/farinspace/jquery.imgpreload.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext5,1);
      });
      }


      //import: marquee.js
      function insertNext5()
      {
      getContent("js/marquee.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext6,1);
      });
      }


      //import: marquee.css
      function insertNext6()
      {

      getContent("css/marquee.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext,1);
      });
      }



      function insertNext()
      {
      setTimeout(pageReadyMan,10);
      }
      }


      // get the content of url and pass that content to specified function
      function getContent( url, callBackFunction )
      {
      // attempt to create the XMLHttpRequest and make the request
      try
      {
      var asyncRequest; // variable to hold XMLHttpRequest object
      asyncRequest = new XMLHttpRequest(); // create request object

      // register event handler
      asyncRequest.onreadystatechange = function(){
      stateChange(asyncRequest, callBackFunction);
      }
      asyncRequest.open( 'GET', url, true ); // prepare the request
      asyncRequest.send( null ); // send the request
      } // end try
      catch ( exception )
      {
      alert( 'Request failed.' );
      } // end catch
      } // end function getContent

      // call function whith content when ready
      function stateChange(asyncRequest, callBackFunction)
      {
      if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
      {
      callBackFunction(asyncRequest.responseText);
      } // end if
      } // end function stateChange


      and the weird part is that all the style's work plus all the javascript functions. the page is frozen for some reason though...










      share|improve this question
















      I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because it takes some time to load. it will be nice if I can display the loader before importing all the:



      <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
      <script type="text/javascript" src="js/myFunctions.js"></script>
      <link type="text/css" href="css/main.css" rel="stylesheet" />
      ...
      ....
      etc


      I have found several tutorials that enable me to import a JavaScript library asynchronously. for example I can do something like:



        (function () {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.async = true;
      s.src = 'js/jquery-ui-1.8.16.custom.min.js';
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      })();


      for some reason when I do the same thing for all my files the pages does not work. I have been trying for so long to try to find where the problem is but I just cannot find it. First I thought that it was probably because some javascript functions depended on the others. but I loaded them in the right order using the time out function when one completed I proceeded with the next and the page still behaves weird. for example I am not able to click on links etc... animations still work though..



      Anyways



      Here is what I have been thinking... I believe browsers have a cache that's why it takes a long time to load the page for the first time and the next time it is quick. so what I am thinking of doing is replacing my index.html page with a page that loads all this files asynchronously. when ajax is done loading all those files redirect to the page that I plan on using. when using that page it should not take long to load since the files should alredy be included on the cache of the browser. on my index page (page where .js and .css file get loaded asynchronously) I don't care of getting errors. I will just be displaying a loader and redirecting the page when done...



      Is this idea a good alternative? or should I keep trying on implementing the asynchronously methods?





      EDIT



      the way I load everything async is like:



      importScripts();

      function importScripts()
      {
      //import: jquery-ui-1.8.16.custom.min.js
      getContent("js/jquery-1.6.2.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      //s.async = true;
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext1,1);
      });


      //import: jquery-ui-1.8.16.custom.min.js
      function insertNext1()
      {
      getContent("js/jquery-ui-1.8.16.custom.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext2,1);
      });
      }

      //import: jquery-ui-1.8.16.custom.css
      function insertNext2()
      {

      getContent("css/custom-theme/jquery-ui-1.8.16.custom.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext3,1);
      });
      }

      //import: main.css
      function insertNext3()
      {

      getContent("css/main.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext4,1);
      });
      }

      //import: jquery.imgpreload.min.js
      function insertNext4()
      {
      getContent("js/farinspace/jquery.imgpreload.min.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext5,1);
      });
      }


      //import: marquee.js
      function insertNext5()
      {
      getContent("js/marquee.js",function (code) {
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext6,1);
      });
      }


      //import: marquee.css
      function insertNext6()
      {

      getContent("css/marquee.css",function (code) {
      var s = document.createElement('link');
      s.type = 'text/css';
      s.rel ="stylesheet";
      s.innerHTML=code;
      var x = document.getElementsByTagName('script')[0];
      x.parentNode.insertBefore(s, x);
      setTimeout(insertNext,1);
      });
      }



      function insertNext()
      {
      setTimeout(pageReadyMan,10);
      }
      }


      // get the content of url and pass that content to specified function
      function getContent( url, callBackFunction )
      {
      // attempt to create the XMLHttpRequest and make the request
      try
      {
      var asyncRequest; // variable to hold XMLHttpRequest object
      asyncRequest = new XMLHttpRequest(); // create request object

      // register event handler
      asyncRequest.onreadystatechange = function(){
      stateChange(asyncRequest, callBackFunction);
      }
      asyncRequest.open( 'GET', url, true ); // prepare the request
      asyncRequest.send( null ); // send the request
      } // end try
      catch ( exception )
      {
      alert( 'Request failed.' );
      } // end catch
      } // end function getContent

      // call function whith content when ready
      function stateChange(asyncRequest, callBackFunction)
      {
      if ( asyncRequest.readyState == 4 && asyncRequest.status == 200 )
      {
      callBackFunction(asyncRequest.responseText);
      } // end if
      } // end function stateChange


      and the weird part is that all the style's work plus all the javascript functions. the page is frozen for some reason though...







      javascript html ajax html5 asynchronous






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 18 '13 at 19:02









      Benjamin

      16.3k30127237




      16.3k30127237










      asked Oct 10 '11 at 21:31









      Tono NamTono Nam

      12.1k61226378




      12.1k61226378
























          19 Answers
          19






          active

          oldest

          votes


















          156














          A couple solutions for async loading:



          //this function will work cross-browser for loading scripts asynchronously
          function loadScript(src, callback)
          {
          var s,
          r,
          t;
          r = false;
          s = document.createElement('script');
          s.type = 'text/javascript';
          s.src = src;
          s.onload = s.onreadystatechange = function() {
          //console.log( this.readyState ); //uncomment this line to see which ready states are called.
          if ( !r && (!this.readyState || this.readyState == 'complete') )
          {
          r = true;
          callback();
          }
          };
          t = document.getElementsByTagName('script')[0];
          t.parentNode.insertBefore(s, t);
          }


          If you've already got jQuery on the page, just use:



          $.getScript(url, successCallback)*



          Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.



          It's not possible to tell specifically what your issue is without seeing the code.



          The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.



          If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).



          * scripts loaded with $.getScript will likely not be cached





          For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:



          function loadScript(src) {
          return new Promise(function (resolve, reject) {
          var s;
          s = document.createElement('script');
          s.src = src;
          s.onload = resolve;
          s.onerror = reject;
          document.head.appendChild(s);
          });
          }


          Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).



          This has the added bonus of being able to detect and handle failures, for example one could call...



          loadScript(cdnSource)
          .catch(loadScript.bind(null, localSource))
          .then(successCallback, failureCallback);


          ...and it would handle CDN outages gracefully.






          share|improve this answer


























          • I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

            – Tono Nam
            Oct 10 '11 at 22:07








          • 1





            I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

            – Tono Nam
            Oct 10 '11 at 22:25






          • 1





            @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

            – zzzzBov
            Oct 12 '11 at 17:38








          • 1





            I had to use t.parentNode.insertBefore (as opposed to t.parent).

            – Phil LaNasa
            Dec 23 '13 at 21:33






          • 1





            @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

            – zzzzBov
            Oct 30 '14 at 1:20



















          29














          HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.



          async - The HTML



          <script async src="siteScript.js" onload="myInit()"></script>


          defer - The HTML



          <script defer src="siteScript.js" onload="myInit()"></script>


          While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async






          share|improve this answer


























          • from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

            – JackDev
            Sep 16 '13 at 1:52






          • 6





            The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

            – shuseel
            Nov 25 '14 at 8:18








          • 1





            "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

            – Stijn de Witt
            Apr 19 '16 at 8:28











          • @StijndeWitt What if Neither async nor defer specified?

            – Mohammed Shareef C
            Nov 11 '16 at 4:44











          • @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

            – Stijn de Witt
            Nov 11 '16 at 20:37



















          7














          I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:



          <!DOCTYPE html>
          <html>
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
          <title>Project Management</title>

          <!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->

          <script type="text/javascript">

          function stylesheet(url) {
          var s = document.createElement('link');
          s.type = 'text/css';
          s.async = true;
          s.src = url;
          var x = document.getElementsByTagName('head')[0];
          x.appendChild(s);
          }

          function script(url) {
          var s = document.createElement('script');
          s.type = 'text/javascript';
          s.async = true;
          s.src = url;
          var x = document.getElementsByTagName('head')[0];
          x.appendChild(s);
          }

          //load scritps to the catche of browser
          (function () {
          stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
          stylesheet('css/main.css');
          stylesheet('css/marquee.css');
          stylesheet('css/mainTable.css');

          script('js/jquery-ui-1.8.16.custom.min.js');
          script('js/jquery-1.6.2.min.js');
          script('js/myFunctions.js');
          script('js/farinspace/jquery.imgpreload.min.js');
          script('js/marquee.js');
          })();

          </script>

          <script type="text/javascript">
          // once the page is loaded go to index2.html
          window.onload = function () {
          document.location = "index2.html";
          }
          </script>

          </head>
          <body>

          <div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>

          <img src="images/home/background.png" />
          <img src="images/home/3.png"/>
          <img src="images/home/6.jpg"/>
          <img src="images/home/4.png"/>
          <img src="images/home/5.png"/>
          <img src="images/home/8.jpg"/>
          <img src="images/home/9.jpg"/>
          <img src="images/logo.png"/>
          <img src="images/logo.png"/>
          <img src="images/theme/contentBorder.png"/>

          </body>
          </html>


          another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.






          share|improve this answer



















          • 8





            and one cant keep wondering how low your pagerank is.

            – Dementic
            Sep 21 '13 at 14:42











          • @Dementic You mean meta tags?

            – Mohammed Shareef C
            Nov 11 '16 at 4:44






          • 1





            @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

            – Stijn de Witt
            Nov 11 '16 at 20:43











          • Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

            – asmmahmud
            Aug 3 '17 at 16:51



















          6














          Example from google



          <script type="text/javascript">
          (function() {
          var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
          po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
          var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
          })();
          </script>





          share|improve this answer

































            6














            Several notes:





            • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)

            • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!


            Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):



            (function() {
            var prot = ("https:"===document.location.protocol?"https://":"http://");

            var scripts = [
            "path/to/first.js",
            "path/to/second.js",
            "path/to/third.js"
            ];

            function completed() { console.log('completed'); } // FIXME: remove logs

            function checkStateAndCall(path, callback) {
            var _success = false;
            return function() {
            if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
            _success = true;
            console.log(path, 'is ready'); // FIXME: remove logs
            callback();
            }
            };
            }

            function asyncLoadScripts(files) {
            function loadNext() { // chain element
            if (!files.length) completed();
            var path = files.shift();
            var scriptElm = document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = true;
            scriptElm.src = prot+path;
            scriptElm.onload = scriptElm.onreadystatechange =
            checkStateAndCall(path, loadNext); // load next file in chain when
            // this one will be ready
            var headElm = document.head || document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
            }
            loadNext(); // start a chain
            }

            asyncLoadScripts(scripts);
            })();





            share|improve this answer





















            • 3





              s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

              – amn
              Jun 28 '16 at 0:17













            • "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

              – BluE
              Feb 27 '18 at 11:37





















            3














            Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:



            <script async>...</script>


            Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).



            Note: There are several ways an external script can be executed:




            • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

            • If async is not present and defer is present: The script is executed when the page has finished parsing

            • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page


            See this: http://www.w3schools.com/tags/att_script_async.asp






            share|improve this answer
























            • Please don't use w3schools as a learning material.

              – tereško
              Dec 4 '17 at 20:32



















            2














            I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:



                function loadScript(src, callback, args) {
            var s, r, t;
            r = false;
            s = document.createElement('script');
            s.type = 'text/javascript';
            s.src = src;
            if (typeof(callback) === 'function') {
            s.onload = s.onreadystatechange = function() {
            if (!r && (!this.readyState || this.readyState === 'complete')) {
            r = true;
            callback.apply(args);
            }
            };
            };
            t = document.getElementsByTagName('script')[0];
            t.parent.insertBefore(s, t);
            }





            share|improve this answer































              2














              Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.



              There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .



              After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.



              In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.



              Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:



              [
              'script1.js',
              'script2.js',
              'script3.js',
              'script4.js'
              ].forEach(function(src) {
              var script = document.createElement('script');
              script.src = src;
              script.async = false;
              document.head.appendChild(script);
              });


              Now, Spec says: Download together, execute in order as soon as all download.



              Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.



              Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.



              IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.



              Everything else says: I’m your friend, we’re going to do this by the book.



              Now, the full code with IE < 10 workaround:



              var scripts = [
              'script1.js',
              'script2.js',
              'script3.js',
              'script4.js'
              ];
              var src;
              var script;
              var pendingScripts = ;
              var firstScript = document.scripts[0];

              // Watch scripts load in IE
              function stateChange() {
              // Execute as many scripts in order as we can
              var pendingScript;
              while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
              pendingScript = pendingScripts.shift();
              // avoid future loading events from this script (eg, if src changes)
              pendingScript.onreadystatechange = null;
              // can't just appendChild, old IE bug if element isn't closed
              firstScript.parentNode.insertBefore(pendingScript, firstScript);
              }
              }

              // loop through our script urls
              while (src = scripts.shift()) {
              if ('async' in firstScript) { // modern browsers
              script = document.createElement('script');
              script.async = false;
              script.src = src;
              document.head.appendChild(script);
              }
              else if (firstScript.readyState) { // IE<10
              // create a script and add it to our todo pile
              script = document.createElement('script');
              pendingScripts.push(script);
              // listen for state changes
              script.onreadystatechange = stateChange;
              // must set src AFTER adding onreadystatechange listener
              // else we’ll miss the loaded event for cached scripts
              script.src = src;
              }
              else { // fall back to defer
              document.write('<script src="' + src + '" defer></'+'script>');
              }
              }





              share|improve this answer































                1














                One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:



                callMyFunctions();


                instead of:



                $(window).load(function() {
                callMyFunctions();
                });


                This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.



                If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.






                share|improve this answer































                  1














                  I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.



                  Here is an example of loading jquery:



                  Modernizr.load([
                  {
                  load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
                  complete: function () {
                  if ( !window.jQuery ) {
                  Modernizr.load('js/libs/jquery-1.6.1.min.js');
                  }
                  }
                  },
                  {
                  // This will wait for the fallback to load and
                  // execute if it needs to.
                  load: 'needs-jQuery.js'
                  }
                  ]);





                  share|improve this answer































                    1














                    I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.



                    export default class ScriptLoader {
                    constructor (options) {
                    const { src, global, protocol = document.location.protocol } = options
                    this.src = src
                    this.global = global
                    this.protocol = protocol
                    this.isLoaded = false
                    }

                    loadScript () {
                    return new Promise((resolve, reject) => {
                    // Create script element and set attributes
                    const script = document.createElement('script')
                    script.type = 'text/javascript'
                    script.async = true
                    script.src = `${this.protocol}//${this.src}`

                    // Append the script to the DOM
                    const el = document.getElementsByTagName('script')[0]
                    el.parentNode.insertBefore(script, el)

                    // Resolve the promise once the script is loaded
                    script.addEventListener('load', () => {
                    this.isLoaded = true
                    resolve(script)
                    })

                    // Catch any errors while loading the script
                    script.addEventListener('error', () => {
                    reject(new Error(`${this.src} failed to load.`))
                    })
                    })
                    }

                    load () {
                    return new Promise(async (resolve, reject) => {
                    if (!this.isLoaded) {
                    try {
                    await this.loadScript()
                    resolve(window[this.global])
                    } catch (e) {
                    reject(e)
                    }
                    } else {
                    resolve(window[this.global])
                    }
                    })
                    }
                    }


                    Usage is like this:



                    const loader = new Loader({
                    src: 'cdn.segment.com/analytics.js',
                    global: 'Segment',
                    })

                    // scriptToLoad will now be a reference to `window.Segment`
                    const scriptToLoad = await loader.load()





                    share|improve this answer































                      1














                      You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript



                      It explains how and when to use such technique.






                      share|improve this answer


























                      • Unfortunately, the link appears to be dead. :(

                        – Eric Seastrand
                        Dec 4 '17 at 20:28











                      • @Eric it's because that is an ancient method of dynamically loading code :D

                        – tereško
                        Dec 4 '17 at 20:31



















                      0














                      Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.



                      Try x.parentNode.appendChild() instead.






                      share|improve this answer































                        0














                        Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.






                        share|improve this answer



















                        • 1





                          Needs jquery...

                          – Abram
                          Mar 7 '16 at 22:23











                        • It's possible to change it a little to get rid of jquery dependency

                          – Stephen L.
                          Mar 29 '16 at 7:26



















                        0














                        You can use LABJS or RequreJS



                        Script loaders like LABJS, RequireJS will improve the speed and quality of your code.






                        share|improve this answer

































                          0














                          Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:



                          fetcInject([
                          'js/jquery-1.6.2.min.js',
                          'js/marquee.js',
                          'css/marquee.css',
                          'css/custom-theme/jquery-ui-1.8.16.custom.css',
                          'css/main.css'
                          ]).then(() => {
                          'js/jquery-ui-1.8.16.custom.min.js',
                          'js/farinspace/jquery.imgpreload.min.js'
                          })


                          For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write.






                          share|improve this answer































                            0














                            Here is my custom solution to eliminate render-blocking JavaScript:



                            // put all your JS files here, in correct order
                            const libs = {
                            "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
                            "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
                            "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
                            "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
                            }
                            const loadedLibs = {}
                            let counter = 0

                            const loadAsync = function(lib) {
                            var http = new XMLHttpRequest()
                            http.open("GET", libs[lib], true)
                            http.onload = () => {
                            loadedLibs[lib] = http.responseText
                            if (++counter == Object.keys(libs).length) startScripts()
                            }
                            http.send()
                            }

                            const startScripts = function() {
                            for (var lib in libs) eval(loadedLibs[lib])
                            console.log("allLoaded")
                            }

                            for (var lib in libs) loadAsync(lib)


                            In short, it loads all your scripts asynchronously, and then executes them consequently.



                            Github repo: https://github.com/mudroljub/js-async-loader






                            share|improve this answer





















                            • 1





                              Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                              – Abram
                              Mar 7 '16 at 22:22






                            • 1





                              That is CORS problem. stackoverflow.com/questions/20035101/…

                              – Damjan Pavlica
                              Dec 21 '17 at 22:59



















                            0














                            Here a little ES6 function if somebody wants to use it in React for example






                            import {uniqueId} from 'lodash' // optional
                            /**
                            * @param {String} file The path of the file you want to load.
                            * @param {Function} callback (optional) The function to call when the script loads.
                            * @param {String} id (optional) The unique id of the file you want to load.
                            */
                            export const loadAsyncScript = (file, callback, id) => {
                            const d = document
                            if (!id) { id = uniqueId('async_script') } // optional
                            if (!d.getElementById(id)) {
                            const tag = 'script'
                            let newScript = d.createElement(tag)
                            let firstScript = d.getElementsByTagName(tag)[0]
                            newScript.id = id
                            newScript.async = true
                            newScript.src = file
                            if (callback) {
                            // IE support
                            newScript.onreadystatechange = () => {
                            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                            newScript.onreadystatechange = null
                            callback(file)
                            }
                            }
                            // Other (non-IE) browsers support
                            newScript.onload = () => {
                            callback(file)
                            }
                            }
                            firstScript.parentNode.insertBefore(newScript, firstScript)
                            } else {
                            console.error(`The script with id ${id} is already loaded`)
                            }
                            }








                            share|improve this answer































                              -3














                              I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.






                              share|improve this answer
























                                Your Answer






                                StackExchange.ifUsing("editor", function () {
                                StackExchange.using("externalEditor", function () {
                                StackExchange.using("snippets", function () {
                                StackExchange.snippets.init();
                                });
                                });
                                }, "code-snippets");

                                StackExchange.ready(function() {
                                var channelOptions = {
                                tags: "".split(" "),
                                id: "1"
                                };
                                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                                StackExchange.using("externalEditor", function() {
                                // Have to fire editor after snippets, if snippets enabled
                                if (StackExchange.settings.snippets.snippetsEnabled) {
                                StackExchange.using("snippets", function() {
                                createEditor();
                                });
                                }
                                else {
                                createEditor();
                                }
                                });

                                function createEditor() {
                                StackExchange.prepareEditor({
                                heartbeatType: 'answer',
                                autoActivateHeartbeat: false,
                                convertImagesToLinks: true,
                                noModals: true,
                                showLowRepImageUploadWarning: true,
                                reputationToPostImages: 10,
                                bindNavPrevention: true,
                                postfix: "",
                                imageUploader: {
                                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                                allowUrls: true
                                },
                                onDemand: true,
                                discardSelector: ".discard-answer"
                                ,immediatelyShowMarkdownHelp:true
                                });


                                }
                                });














                                draft saved

                                draft discarded


















                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7718935%2fload-scripts-asynchronously%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown

























                                19 Answers
                                19






                                active

                                oldest

                                votes








                                19 Answers
                                19






                                active

                                oldest

                                votes









                                active

                                oldest

                                votes






                                active

                                oldest

                                votes









                                156














                                A couple solutions for async loading:



                                //this function will work cross-browser for loading scripts asynchronously
                                function loadScript(src, callback)
                                {
                                var s,
                                r,
                                t;
                                r = false;
                                s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.src = src;
                                s.onload = s.onreadystatechange = function() {
                                //console.log( this.readyState ); //uncomment this line to see which ready states are called.
                                if ( !r && (!this.readyState || this.readyState == 'complete') )
                                {
                                r = true;
                                callback();
                                }
                                };
                                t = document.getElementsByTagName('script')[0];
                                t.parentNode.insertBefore(s, t);
                                }


                                If you've already got jQuery on the page, just use:



                                $.getScript(url, successCallback)*



                                Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.



                                It's not possible to tell specifically what your issue is without seeing the code.



                                The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.



                                If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).



                                * scripts loaded with $.getScript will likely not be cached





                                For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:



                                function loadScript(src) {
                                return new Promise(function (resolve, reject) {
                                var s;
                                s = document.createElement('script');
                                s.src = src;
                                s.onload = resolve;
                                s.onerror = reject;
                                document.head.appendChild(s);
                                });
                                }


                                Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).



                                This has the added bonus of being able to detect and handle failures, for example one could call...



                                loadScript(cdnSource)
                                .catch(loadScript.bind(null, localSource))
                                .then(successCallback, failureCallback);


                                ...and it would handle CDN outages gracefully.






                                share|improve this answer


























                                • I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                  – Tono Nam
                                  Oct 10 '11 at 22:07








                                • 1





                                  I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                  – Tono Nam
                                  Oct 10 '11 at 22:25






                                • 1





                                  @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                  – zzzzBov
                                  Oct 12 '11 at 17:38








                                • 1





                                  I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                  – Phil LaNasa
                                  Dec 23 '13 at 21:33






                                • 1





                                  @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                  – zzzzBov
                                  Oct 30 '14 at 1:20
















                                156














                                A couple solutions for async loading:



                                //this function will work cross-browser for loading scripts asynchronously
                                function loadScript(src, callback)
                                {
                                var s,
                                r,
                                t;
                                r = false;
                                s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.src = src;
                                s.onload = s.onreadystatechange = function() {
                                //console.log( this.readyState ); //uncomment this line to see which ready states are called.
                                if ( !r && (!this.readyState || this.readyState == 'complete') )
                                {
                                r = true;
                                callback();
                                }
                                };
                                t = document.getElementsByTagName('script')[0];
                                t.parentNode.insertBefore(s, t);
                                }


                                If you've already got jQuery on the page, just use:



                                $.getScript(url, successCallback)*



                                Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.



                                It's not possible to tell specifically what your issue is without seeing the code.



                                The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.



                                If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).



                                * scripts loaded with $.getScript will likely not be cached





                                For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:



                                function loadScript(src) {
                                return new Promise(function (resolve, reject) {
                                var s;
                                s = document.createElement('script');
                                s.src = src;
                                s.onload = resolve;
                                s.onerror = reject;
                                document.head.appendChild(s);
                                });
                                }


                                Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).



                                This has the added bonus of being able to detect and handle failures, for example one could call...



                                loadScript(cdnSource)
                                .catch(loadScript.bind(null, localSource))
                                .then(successCallback, failureCallback);


                                ...and it would handle CDN outages gracefully.






                                share|improve this answer


























                                • I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                  – Tono Nam
                                  Oct 10 '11 at 22:07








                                • 1





                                  I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                  – Tono Nam
                                  Oct 10 '11 at 22:25






                                • 1





                                  @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                  – zzzzBov
                                  Oct 12 '11 at 17:38








                                • 1





                                  I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                  – Phil LaNasa
                                  Dec 23 '13 at 21:33






                                • 1





                                  @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                  – zzzzBov
                                  Oct 30 '14 at 1:20














                                156












                                156








                                156







                                A couple solutions for async loading:



                                //this function will work cross-browser for loading scripts asynchronously
                                function loadScript(src, callback)
                                {
                                var s,
                                r,
                                t;
                                r = false;
                                s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.src = src;
                                s.onload = s.onreadystatechange = function() {
                                //console.log( this.readyState ); //uncomment this line to see which ready states are called.
                                if ( !r && (!this.readyState || this.readyState == 'complete') )
                                {
                                r = true;
                                callback();
                                }
                                };
                                t = document.getElementsByTagName('script')[0];
                                t.parentNode.insertBefore(s, t);
                                }


                                If you've already got jQuery on the page, just use:



                                $.getScript(url, successCallback)*



                                Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.



                                It's not possible to tell specifically what your issue is without seeing the code.



                                The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.



                                If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).



                                * scripts loaded with $.getScript will likely not be cached





                                For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:



                                function loadScript(src) {
                                return new Promise(function (resolve, reject) {
                                var s;
                                s = document.createElement('script');
                                s.src = src;
                                s.onload = resolve;
                                s.onerror = reject;
                                document.head.appendChild(s);
                                });
                                }


                                Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).



                                This has the added bonus of being able to detect and handle failures, for example one could call...



                                loadScript(cdnSource)
                                .catch(loadScript.bind(null, localSource))
                                .then(successCallback, failureCallback);


                                ...and it would handle CDN outages gracefully.






                                share|improve this answer















                                A couple solutions for async loading:



                                //this function will work cross-browser for loading scripts asynchronously
                                function loadScript(src, callback)
                                {
                                var s,
                                r,
                                t;
                                r = false;
                                s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.src = src;
                                s.onload = s.onreadystatechange = function() {
                                //console.log( this.readyState ); //uncomment this line to see which ready states are called.
                                if ( !r && (!this.readyState || this.readyState == 'complete') )
                                {
                                r = true;
                                callback();
                                }
                                };
                                t = document.getElementsByTagName('script')[0];
                                t.parentNode.insertBefore(s, t);
                                }


                                If you've already got jQuery on the page, just use:



                                $.getScript(url, successCallback)*



                                Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready before events can be bound to the elements.



                                It's not possible to tell specifically what your issue is without seeing the code.



                                The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.



                                If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).



                                * scripts loaded with $.getScript will likely not be cached





                                For anyone who can use modern features such as the Promise object, the loadScript function has become significantly simpler:



                                function loadScript(src) {
                                return new Promise(function (resolve, reject) {
                                var s;
                                s = document.createElement('script');
                                s.src = src;
                                s.onload = resolve;
                                s.onerror = reject;
                                document.head.appendChild(s);
                                });
                                }


                                Be aware that this version no longer accepts a callback argument as the returned promise will handle callback. What previously would have been loadScript(src, callback) would now be loadScript(src).then(callback).



                                This has the added bonus of being able to detect and handle failures, for example one could call...



                                loadScript(cdnSource)
                                .catch(loadScript.bind(null, localSource))
                                .then(successCallback, failureCallback);


                                ...and it would handle CDN outages gracefully.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Feb 20 '17 at 2:31

























                                answered Oct 10 '11 at 22:00









                                zzzzBovzzzzBov

                                133k34267308




                                133k34267308













                                • I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                  – Tono Nam
                                  Oct 10 '11 at 22:07








                                • 1





                                  I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                  – Tono Nam
                                  Oct 10 '11 at 22:25






                                • 1





                                  @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                  – zzzzBov
                                  Oct 12 '11 at 17:38








                                • 1





                                  I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                  – Phil LaNasa
                                  Dec 23 '13 at 21:33






                                • 1





                                  @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                  – zzzzBov
                                  Oct 30 '14 at 1:20



















                                • I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                  – Tono Nam
                                  Oct 10 '11 at 22:07








                                • 1





                                  I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                  – Tono Nam
                                  Oct 10 '11 at 22:25






                                • 1





                                  @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                  – zzzzBov
                                  Oct 12 '11 at 17:38








                                • 1





                                  I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                  – Phil LaNasa
                                  Dec 23 '13 at 21:33






                                • 1





                                  @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                  – zzzzBov
                                  Oct 30 '14 at 1:20

















                                I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                – Tono Nam
                                Oct 10 '11 at 22:07







                                I am about to start trying that out. but if I load those scripts on a different page when I redirect the page to a different page and that page happens to have the same scripts they should not take time to load. they should be in the cache right? so should't I implement that technique instead?

                                – Tono Nam
                                Oct 10 '11 at 22:07






                                1




                                1





                                I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                – Tono Nam
                                Oct 10 '11 at 22:25





                                I changed and appended the child to the head tag instead of the body... ..var x = document.getElementsByTagName('head')[0]; x.appendChild(s);

                                – Tono Nam
                                Oct 10 '11 at 22:25




                                1




                                1





                                @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                – zzzzBov
                                Oct 12 '11 at 17:38







                                @TonoNam, you could just use document.head.appendChild, however there are some niche issues with adding scripts to the <head>; nothing that would prevent scripts from loading and executing.

                                – zzzzBov
                                Oct 12 '11 at 17:38






                                1




                                1





                                I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                – Phil LaNasa
                                Dec 23 '13 at 21:33





                                I had to use t.parentNode.insertBefore (as opposed to t.parent).

                                – Phil LaNasa
                                Dec 23 '13 at 21:33




                                1




                                1





                                @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                – zzzzBov
                                Oct 30 '14 at 1:20





                                @MuhammadUmer, if you're writing an additional script tag with document.write before the document has loaded, the script will be executed synchronously as part of loading the page, and will not include any asynchronous callback behavior on its own. If you're creating a script element and adding it to the page, then you'll have access to add event listeners to trigger asynchronously. tl;dr: it depends on how you're loading the script with JS.

                                – zzzzBov
                                Oct 30 '14 at 1:20













                                29














                                HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.



                                async - The HTML



                                <script async src="siteScript.js" onload="myInit()"></script>


                                defer - The HTML



                                <script defer src="siteScript.js" onload="myInit()"></script>


                                While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async






                                share|improve this answer


























                                • from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                  – JackDev
                                  Sep 16 '13 at 1:52






                                • 6





                                  The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                  – shuseel
                                  Nov 25 '14 at 8:18








                                • 1





                                  "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                  – Stijn de Witt
                                  Apr 19 '16 at 8:28











                                • @StijndeWitt What if Neither async nor defer specified?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44











                                • @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:37
















                                29














                                HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.



                                async - The HTML



                                <script async src="siteScript.js" onload="myInit()"></script>


                                defer - The HTML



                                <script defer src="siteScript.js" onload="myInit()"></script>


                                While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async






                                share|improve this answer


























                                • from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                  – JackDev
                                  Sep 16 '13 at 1:52






                                • 6





                                  The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                  – shuseel
                                  Nov 25 '14 at 8:18








                                • 1





                                  "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                  – Stijn de Witt
                                  Apr 19 '16 at 8:28











                                • @StijndeWitt What if Neither async nor defer specified?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44











                                • @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:37














                                29












                                29








                                29







                                HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.



                                async - The HTML



                                <script async src="siteScript.js" onload="myInit()"></script>


                                defer - The HTML



                                <script defer src="siteScript.js" onload="myInit()"></script>


                                While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async






                                share|improve this answer















                                HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.



                                async - The HTML



                                <script async src="siteScript.js" onload="myInit()"></script>


                                defer - The HTML



                                <script defer src="siteScript.js" onload="myInit()"></script>


                                While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 23 '13 at 21:27

























                                answered Aug 23 '13 at 21:16









                                Donald PorterDonald Porter

                                46344




                                46344













                                • from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                  – JackDev
                                  Sep 16 '13 at 1:52






                                • 6





                                  The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                  – shuseel
                                  Nov 25 '14 at 8:18








                                • 1





                                  "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                  – Stijn de Witt
                                  Apr 19 '16 at 8:28











                                • @StijndeWitt What if Neither async nor defer specified?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44











                                • @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:37



















                                • from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                  – JackDev
                                  Sep 16 '13 at 1:52






                                • 6





                                  The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                  – shuseel
                                  Nov 25 '14 at 8:18








                                • 1





                                  "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                  – Stijn de Witt
                                  Apr 19 '16 at 8:28











                                • @StijndeWitt What if Neither async nor defer specified?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44











                                • @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:37

















                                from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                – JackDev
                                Sep 16 '13 at 1:52





                                from my understanding after reading stackoverflow.com/questions/2774373/…, asyn is not for loading, but for determining when to run the javascript contained.

                                – JackDev
                                Sep 16 '13 at 1:52




                                6




                                6





                                The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                – shuseel
                                Nov 25 '14 at 8:18







                                The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded

                                – shuseel
                                Nov 25 '14 at 8:18






                                1




                                1





                                "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                – Stijn de Witt
                                Apr 19 '16 at 8:28





                                "asyn is not for loading, but for determining when to run the javascript contained" This is not contradictory; In all cases, the browser will start loading the script ASAP. But without async or defer it will block the rendering while it loads. Setting async will tell it to not block and run the script ASAP. Setting defer will tell it to not block but wait with running the script until the page is done. Usually it's no problem to run scripts ASAP as long as they don't have any dependencies (e.g. jQuery). If one script has dependencies on another, use onLoad to wait for it.

                                – Stijn de Witt
                                Apr 19 '16 at 8:28













                                @StijndeWitt What if Neither async nor defer specified?

                                – Mohammed Shareef C
                                Nov 11 '16 at 4:44





                                @StijndeWitt What if Neither async nor defer specified?

                                – Mohammed Shareef C
                                Nov 11 '16 at 4:44













                                @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                – Stijn de Witt
                                Nov 11 '16 at 20:37





                                @MohammedShareefC If you specify neither, you get something closely resembling sync behaviour; the browser blocks further processing while it downloads and runs the script. So effectively the default behavior is sync. But because this is detrimental for performance, browsers will work around it as much as they can. They can go ahead with parsing, loading and applying CSS etc... They cannot however start running the next script fragment. So stuff will block. By setting async, you are telling the browser that it's ok to go ahead and you will make sure that you make it work yourself.

                                – Stijn de Witt
                                Nov 11 '16 at 20:37











                                7














                                I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:



                                <!DOCTYPE html>
                                <html>
                                <head>
                                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                <title>Project Management</title>

                                <!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->

                                <script type="text/javascript">

                                function stylesheet(url) {
                                var s = document.createElement('link');
                                s.type = 'text/css';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                function script(url) {
                                var s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                //load scritps to the catche of browser
                                (function () {
                                stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
                                stylesheet('css/main.css');
                                stylesheet('css/marquee.css');
                                stylesheet('css/mainTable.css');

                                script('js/jquery-ui-1.8.16.custom.min.js');
                                script('js/jquery-1.6.2.min.js');
                                script('js/myFunctions.js');
                                script('js/farinspace/jquery.imgpreload.min.js');
                                script('js/marquee.js');
                                })();

                                </script>

                                <script type="text/javascript">
                                // once the page is loaded go to index2.html
                                window.onload = function () {
                                document.location = "index2.html";
                                }
                                </script>

                                </head>
                                <body>

                                <div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>

                                <img src="images/home/background.png" />
                                <img src="images/home/3.png"/>
                                <img src="images/home/6.jpg"/>
                                <img src="images/home/4.png"/>
                                <img src="images/home/5.png"/>
                                <img src="images/home/8.jpg"/>
                                <img src="images/home/9.jpg"/>
                                <img src="images/logo.png"/>
                                <img src="images/logo.png"/>
                                <img src="images/theme/contentBorder.png"/>

                                </body>
                                </html>


                                another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.






                                share|improve this answer



















                                • 8





                                  and one cant keep wondering how low your pagerank is.

                                  – Dementic
                                  Sep 21 '13 at 14:42











                                • @Dementic You mean meta tags?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44






                                • 1





                                  @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:43











                                • Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                  – asmmahmud
                                  Aug 3 '17 at 16:51
















                                7














                                I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:



                                <!DOCTYPE html>
                                <html>
                                <head>
                                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                <title>Project Management</title>

                                <!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->

                                <script type="text/javascript">

                                function stylesheet(url) {
                                var s = document.createElement('link');
                                s.type = 'text/css';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                function script(url) {
                                var s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                //load scritps to the catche of browser
                                (function () {
                                stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
                                stylesheet('css/main.css');
                                stylesheet('css/marquee.css');
                                stylesheet('css/mainTable.css');

                                script('js/jquery-ui-1.8.16.custom.min.js');
                                script('js/jquery-1.6.2.min.js');
                                script('js/myFunctions.js');
                                script('js/farinspace/jquery.imgpreload.min.js');
                                script('js/marquee.js');
                                })();

                                </script>

                                <script type="text/javascript">
                                // once the page is loaded go to index2.html
                                window.onload = function () {
                                document.location = "index2.html";
                                }
                                </script>

                                </head>
                                <body>

                                <div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>

                                <img src="images/home/background.png" />
                                <img src="images/home/3.png"/>
                                <img src="images/home/6.jpg"/>
                                <img src="images/home/4.png"/>
                                <img src="images/home/5.png"/>
                                <img src="images/home/8.jpg"/>
                                <img src="images/home/9.jpg"/>
                                <img src="images/logo.png"/>
                                <img src="images/logo.png"/>
                                <img src="images/theme/contentBorder.png"/>

                                </body>
                                </html>


                                another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.






                                share|improve this answer



















                                • 8





                                  and one cant keep wondering how low your pagerank is.

                                  – Dementic
                                  Sep 21 '13 at 14:42











                                • @Dementic You mean meta tags?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44






                                • 1





                                  @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:43











                                • Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                  – asmmahmud
                                  Aug 3 '17 at 16:51














                                7












                                7








                                7







                                I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:



                                <!DOCTYPE html>
                                <html>
                                <head>
                                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                <title>Project Management</title>

                                <!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->

                                <script type="text/javascript">

                                function stylesheet(url) {
                                var s = document.createElement('link');
                                s.type = 'text/css';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                function script(url) {
                                var s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                //load scritps to the catche of browser
                                (function () {
                                stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
                                stylesheet('css/main.css');
                                stylesheet('css/marquee.css');
                                stylesheet('css/mainTable.css');

                                script('js/jquery-ui-1.8.16.custom.min.js');
                                script('js/jquery-1.6.2.min.js');
                                script('js/myFunctions.js');
                                script('js/farinspace/jquery.imgpreload.min.js');
                                script('js/marquee.js');
                                })();

                                </script>

                                <script type="text/javascript">
                                // once the page is loaded go to index2.html
                                window.onload = function () {
                                document.location = "index2.html";
                                }
                                </script>

                                </head>
                                <body>

                                <div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>

                                <img src="images/home/background.png" />
                                <img src="images/home/3.png"/>
                                <img src="images/home/6.jpg"/>
                                <img src="images/home/4.png"/>
                                <img src="images/home/5.png"/>
                                <img src="images/home/8.jpg"/>
                                <img src="images/home/9.jpg"/>
                                <img src="images/logo.png"/>
                                <img src="images/logo.png"/>
                                <img src="images/theme/contentBorder.png"/>

                                </body>
                                </html>


                                another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.






                                share|improve this answer













                                I loaded the scripts asynchronously (html 5 has that feature) when all the scripts where done loading I redirected the page to index2.html where index2.html uses the same libraries. Because browsers have a cache once the page redirects to index2.html, index2.html loads in less than a second because it has all it needs to load the page. In my index.html page I also load the images that I plan on using so that the browser place those images on the cache. so my index.html looks like:



                                <!DOCTYPE html>
                                <html>
                                <head>
                                <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                <title>Project Management</title>

                                <!-- the purpose of this page is to load all the scripts on the browsers cache so that pages can load fast from now on -->

                                <script type="text/javascript">

                                function stylesheet(url) {
                                var s = document.createElement('link');
                                s.type = 'text/css';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                function script(url) {
                                var s = document.createElement('script');
                                s.type = 'text/javascript';
                                s.async = true;
                                s.src = url;
                                var x = document.getElementsByTagName('head')[0];
                                x.appendChild(s);
                                }

                                //load scritps to the catche of browser
                                (function () {
                                stylesheet('css/custom-theme/jquery-ui-1.8.16.custom.css');
                                stylesheet('css/main.css');
                                stylesheet('css/marquee.css');
                                stylesheet('css/mainTable.css');

                                script('js/jquery-ui-1.8.16.custom.min.js');
                                script('js/jquery-1.6.2.min.js');
                                script('js/myFunctions.js');
                                script('js/farinspace/jquery.imgpreload.min.js');
                                script('js/marquee.js');
                                })();

                                </script>

                                <script type="text/javascript">
                                // once the page is loaded go to index2.html
                                window.onload = function () {
                                document.location = "index2.html";
                                }
                                </script>

                                </head>
                                <body>

                                <div id="cover" style="position:fixed; left:0px; top:0px; width:100%; height:100%; background-color:Black; z-index:100;">Loading</div>

                                <img src="images/home/background.png" />
                                <img src="images/home/3.png"/>
                                <img src="images/home/6.jpg"/>
                                <img src="images/home/4.png"/>
                                <img src="images/home/5.png"/>
                                <img src="images/home/8.jpg"/>
                                <img src="images/home/9.jpg"/>
                                <img src="images/logo.png"/>
                                <img src="images/logo.png"/>
                                <img src="images/theme/contentBorder.png"/>

                                </body>
                                </html>


                                another nice thing about this is that I may place a loader in the page and when the page is done loading the loader will go away and in a matte of milliseconds the new page will be running.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Oct 12 '11 at 16:02









                                Tono NamTono Nam

                                12.1k61226378




                                12.1k61226378








                                • 8





                                  and one cant keep wondering how low your pagerank is.

                                  – Dementic
                                  Sep 21 '13 at 14:42











                                • @Dementic You mean meta tags?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44






                                • 1





                                  @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:43











                                • Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                  – asmmahmud
                                  Aug 3 '17 at 16:51














                                • 8





                                  and one cant keep wondering how low your pagerank is.

                                  – Dementic
                                  Sep 21 '13 at 14:42











                                • @Dementic You mean meta tags?

                                  – Mohammed Shareef C
                                  Nov 11 '16 at 4:44






                                • 1





                                  @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                  – Stijn de Witt
                                  Nov 11 '16 at 20:43











                                • Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                  – asmmahmud
                                  Aug 3 '17 at 16:51








                                8




                                8





                                and one cant keep wondering how low your pagerank is.

                                – Dementic
                                Sep 21 '13 at 14:42





                                and one cant keep wondering how low your pagerank is.

                                – Dementic
                                Sep 21 '13 at 14:42













                                @Dementic You mean meta tags?

                                – Mohammed Shareef C
                                Nov 11 '16 at 4:44





                                @Dementic You mean meta tags?

                                – Mohammed Shareef C
                                Nov 11 '16 at 4:44




                                1




                                1





                                @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                – Stijn de Witt
                                Nov 11 '16 at 20:43





                                @MohammedShareefC It's irony. A special page just to preload stuff doesn't sound like a good idea SEO wise. Preloading is great, but you don't need to redirect to achieve it. Just stick the links in a hidden div and the browser will take care of it for you automatically. Then don't redirect but just render the actual page. COPY-PASTERS READ THIS: Please change the ISO-88591 encoding to UTF-8 before using any of this HTML so the rest of us can get out of encoding hell anytime soon. Thanks!

                                – Stijn de Witt
                                Nov 11 '16 at 20:43













                                Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                – asmmahmud
                                Aug 3 '17 at 16:51





                                Please look at my new answer: stackoverflow.com/questions/7718935/load-scripts-asynchronously/…

                                – asmmahmud
                                Aug 3 '17 at 16:51











                                6














                                Example from google



                                <script type="text/javascript">
                                (function() {
                                var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                                po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
                                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                                })();
                                </script>





                                share|improve this answer






























                                  6














                                  Example from google



                                  <script type="text/javascript">
                                  (function() {
                                  var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                                  po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
                                  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                                  })();
                                  </script>





                                  share|improve this answer




























                                    6












                                    6








                                    6







                                    Example from google



                                    <script type="text/javascript">
                                    (function() {
                                    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                                    po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
                                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                                    })();
                                    </script>





                                    share|improve this answer















                                    Example from google



                                    <script type="text/javascript">
                                    (function() {
                                    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
                                    po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
                                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
                                    })();
                                    </script>






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Dec 26 '13 at 13:36









                                    kleopatra

                                    45.3k1676163




                                    45.3k1676163










                                    answered Dec 26 '13 at 13:29









                                    Kernel MedKernel Med

                                    101411




                                    101411























                                        6














                                        Several notes:





                                        • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)

                                        • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!


                                        Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):



                                        (function() {
                                        var prot = ("https:"===document.location.protocol?"https://":"http://");

                                        var scripts = [
                                        "path/to/first.js",
                                        "path/to/second.js",
                                        "path/to/third.js"
                                        ];

                                        function completed() { console.log('completed'); } // FIXME: remove logs

                                        function checkStateAndCall(path, callback) {
                                        var _success = false;
                                        return function() {
                                        if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                                        _success = true;
                                        console.log(path, 'is ready'); // FIXME: remove logs
                                        callback();
                                        }
                                        };
                                        }

                                        function asyncLoadScripts(files) {
                                        function loadNext() { // chain element
                                        if (!files.length) completed();
                                        var path = files.shift();
                                        var scriptElm = document.createElement('script');
                                        scriptElm.type = 'text/javascript';
                                        scriptElm.async = true;
                                        scriptElm.src = prot+path;
                                        scriptElm.onload = scriptElm.onreadystatechange =
                                        checkStateAndCall(path, loadNext); // load next file in chain when
                                        // this one will be ready
                                        var headElm = document.head || document.getElementsByTagName('head')[0];
                                        headElm.appendChild(scriptElm);
                                        }
                                        loadNext(); // start a chain
                                        }

                                        asyncLoadScripts(scripts);
                                        })();





                                        share|improve this answer





















                                        • 3





                                          s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                          – amn
                                          Jun 28 '16 at 0:17













                                        • "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                          – BluE
                                          Feb 27 '18 at 11:37


















                                        6














                                        Several notes:





                                        • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)

                                        • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!


                                        Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):



                                        (function() {
                                        var prot = ("https:"===document.location.protocol?"https://":"http://");

                                        var scripts = [
                                        "path/to/first.js",
                                        "path/to/second.js",
                                        "path/to/third.js"
                                        ];

                                        function completed() { console.log('completed'); } // FIXME: remove logs

                                        function checkStateAndCall(path, callback) {
                                        var _success = false;
                                        return function() {
                                        if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                                        _success = true;
                                        console.log(path, 'is ready'); // FIXME: remove logs
                                        callback();
                                        }
                                        };
                                        }

                                        function asyncLoadScripts(files) {
                                        function loadNext() { // chain element
                                        if (!files.length) completed();
                                        var path = files.shift();
                                        var scriptElm = document.createElement('script');
                                        scriptElm.type = 'text/javascript';
                                        scriptElm.async = true;
                                        scriptElm.src = prot+path;
                                        scriptElm.onload = scriptElm.onreadystatechange =
                                        checkStateAndCall(path, loadNext); // load next file in chain when
                                        // this one will be ready
                                        var headElm = document.head || document.getElementsByTagName('head')[0];
                                        headElm.appendChild(scriptElm);
                                        }
                                        loadNext(); // start a chain
                                        }

                                        asyncLoadScripts(scripts);
                                        })();





                                        share|improve this answer





















                                        • 3





                                          s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                          – amn
                                          Jun 28 '16 at 0:17













                                        • "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                          – BluE
                                          Feb 27 '18 at 11:37
















                                        6












                                        6








                                        6







                                        Several notes:





                                        • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)

                                        • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!


                                        Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):



                                        (function() {
                                        var prot = ("https:"===document.location.protocol?"https://":"http://");

                                        var scripts = [
                                        "path/to/first.js",
                                        "path/to/second.js",
                                        "path/to/third.js"
                                        ];

                                        function completed() { console.log('completed'); } // FIXME: remove logs

                                        function checkStateAndCall(path, callback) {
                                        var _success = false;
                                        return function() {
                                        if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                                        _success = true;
                                        console.log(path, 'is ready'); // FIXME: remove logs
                                        callback();
                                        }
                                        };
                                        }

                                        function asyncLoadScripts(files) {
                                        function loadNext() { // chain element
                                        if (!files.length) completed();
                                        var path = files.shift();
                                        var scriptElm = document.createElement('script');
                                        scriptElm.type = 'text/javascript';
                                        scriptElm.async = true;
                                        scriptElm.src = prot+path;
                                        scriptElm.onload = scriptElm.onreadystatechange =
                                        checkStateAndCall(path, loadNext); // load next file in chain when
                                        // this one will be ready
                                        var headElm = document.head || document.getElementsByTagName('head')[0];
                                        headElm.appendChild(scriptElm);
                                        }
                                        loadNext(); // start a chain
                                        }

                                        asyncLoadScripts(scripts);
                                        })();





                                        share|improve this answer















                                        Several notes:





                                        • s.async = true is not very correct for HTML5 doctype, correct is s.async = 'async' (actually using true is correct, thanks to amn who pointed it out in the comment just below)

                                        • Using timeouts to control the order is not very good and safe, and you also make the loading time much larger, to equal the sum of all timeouts!


                                        Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example (remove console.log for production use :) ):



                                        (function() {
                                        var prot = ("https:"===document.location.protocol?"https://":"http://");

                                        var scripts = [
                                        "path/to/first.js",
                                        "path/to/second.js",
                                        "path/to/third.js"
                                        ];

                                        function completed() { console.log('completed'); } // FIXME: remove logs

                                        function checkStateAndCall(path, callback) {
                                        var _success = false;
                                        return function() {
                                        if (!_success && (!this.readyState || (this.readyState == 'complete'))) {
                                        _success = true;
                                        console.log(path, 'is ready'); // FIXME: remove logs
                                        callback();
                                        }
                                        };
                                        }

                                        function asyncLoadScripts(files) {
                                        function loadNext() { // chain element
                                        if (!files.length) completed();
                                        var path = files.shift();
                                        var scriptElm = document.createElement('script');
                                        scriptElm.type = 'text/javascript';
                                        scriptElm.async = true;
                                        scriptElm.src = prot+path;
                                        scriptElm.onload = scriptElm.onreadystatechange =
                                        checkStateAndCall(path, loadNext); // load next file in chain when
                                        // this one will be ready
                                        var headElm = document.head || document.getElementsByTagName('head')[0];
                                        headElm.appendChild(scriptElm);
                                        }
                                        loadNext(); // start a chain
                                        }

                                        asyncLoadScripts(scripts);
                                        })();






                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited May 23 '17 at 12:18









                                        Community

                                        11




                                        11










                                        answered Feb 11 '13 at 14:20









                                        shaman.sirshaman.sir

                                        2,27832235




                                        2,27832235








                                        • 3





                                          s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                          – amn
                                          Jun 28 '16 at 0:17













                                        • "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                          – BluE
                                          Feb 27 '18 at 11:37
















                                        • 3





                                          s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                          – amn
                                          Jun 28 '16 at 0:17













                                        • "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                          – BluE
                                          Feb 27 '18 at 11:37










                                        3




                                        3





                                        s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                        – amn
                                        Jun 28 '16 at 0:17







                                        s.async = true is correct. The property async is specified explicitly as a boolean in W3C's HTML 5 recommendation at w3.org/TR/html5/scripting-1.html#attr-script-async. You are confusing the async attribute with the async property exposed by objects implementing the HTMLScriptElement DOM interface. Indeed, when manipulating the corresponding attribute of the element through something like Element.setAttribute, you should use element.setAttribute("async", "async") as all HTML attributes are first and foremost text.

                                        – amn
                                        Jun 28 '16 at 0:17















                                        "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                        – BluE
                                        Feb 27 '18 at 11:37







                                        "Since there is a recent reason to load files asynchronously, but in order, I'd recommend a bit more functional-driven way over your example [...]". I know async is usually "better", but what "recent" reason are you refering to?

                                        – BluE
                                        Feb 27 '18 at 11:37













                                        3














                                        Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:



                                        <script async>...</script>


                                        Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).



                                        Note: There are several ways an external script can be executed:




                                        • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

                                        • If async is not present and defer is present: The script is executed when the page has finished parsing

                                        • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page


                                        See this: http://www.w3schools.com/tags/att_script_async.asp






                                        share|improve this answer
























                                        • Please don't use w3schools as a learning material.

                                          – tereško
                                          Dec 4 '17 at 20:32
















                                        3














                                        Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:



                                        <script async>...</script>


                                        Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).



                                        Note: There are several ways an external script can be executed:




                                        • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

                                        • If async is not present and defer is present: The script is executed when the page has finished parsing

                                        • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page


                                        See this: http://www.w3schools.com/tags/att_script_async.asp






                                        share|improve this answer
























                                        • Please don't use w3schools as a learning material.

                                          – tereško
                                          Dec 4 '17 at 20:32














                                        3












                                        3








                                        3







                                        Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:



                                        <script async>...</script>


                                        Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).



                                        Note: There are several ways an external script can be executed:




                                        • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

                                        • If async is not present and defer is present: The script is executed when the page has finished parsing

                                        • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page


                                        See this: http://www.w3schools.com/tags/att_script_async.asp






                                        share|improve this answer













                                        Thanks to HTML5, you can now declare the scripts that you want to load asynchronously by adding "async" in the tag:



                                        <script async>...</script>


                                        Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).



                                        Note: There are several ways an external script can be executed:




                                        • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)

                                        • If async is not present and defer is present: The script is executed when the page has finished parsing

                                        • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page


                                        See this: http://www.w3schools.com/tags/att_script_async.asp







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered May 9 '16 at 15:08









                                        odrozodroz

                                        916




                                        916













                                        • Please don't use w3schools as a learning material.

                                          – tereško
                                          Dec 4 '17 at 20:32



















                                        • Please don't use w3schools as a learning material.

                                          – tereško
                                          Dec 4 '17 at 20:32

















                                        Please don't use w3schools as a learning material.

                                        – tereško
                                        Dec 4 '17 at 20:32





                                        Please don't use w3schools as a learning material.

                                        – tereško
                                        Dec 4 '17 at 20:32











                                        2














                                        I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:



                                            function loadScript(src, callback, args) {
                                        var s, r, t;
                                        r = false;
                                        s = document.createElement('script');
                                        s.type = 'text/javascript';
                                        s.src = src;
                                        if (typeof(callback) === 'function') {
                                        s.onload = s.onreadystatechange = function() {
                                        if (!r && (!this.readyState || this.readyState === 'complete')) {
                                        r = true;
                                        callback.apply(args);
                                        }
                                        };
                                        };
                                        t = document.getElementsByTagName('script')[0];
                                        t.parent.insertBefore(s, t);
                                        }





                                        share|improve this answer




























                                          2














                                          I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:



                                              function loadScript(src, callback, args) {
                                          var s, r, t;
                                          r = false;
                                          s = document.createElement('script');
                                          s.type = 'text/javascript';
                                          s.src = src;
                                          if (typeof(callback) === 'function') {
                                          s.onload = s.onreadystatechange = function() {
                                          if (!r && (!this.readyState || this.readyState === 'complete')) {
                                          r = true;
                                          callback.apply(args);
                                          }
                                          };
                                          };
                                          t = document.getElementsByTagName('script')[0];
                                          t.parent.insertBefore(s, t);
                                          }





                                          share|improve this answer


























                                            2












                                            2








                                            2







                                            I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:



                                                function loadScript(src, callback, args) {
                                            var s, r, t;
                                            r = false;
                                            s = document.createElement('script');
                                            s.type = 'text/javascript';
                                            s.src = src;
                                            if (typeof(callback) === 'function') {
                                            s.onload = s.onreadystatechange = function() {
                                            if (!r && (!this.readyState || this.readyState === 'complete')) {
                                            r = true;
                                            callback.apply(args);
                                            }
                                            };
                                            };
                                            t = document.getElementsByTagName('script')[0];
                                            t.parent.insertBefore(s, t);
                                            }





                                            share|improve this answer













                                            I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:



                                                function loadScript(src, callback, args) {
                                            var s, r, t;
                                            r = false;
                                            s = document.createElement('script');
                                            s.type = 'text/javascript';
                                            s.src = src;
                                            if (typeof(callback) === 'function') {
                                            s.onload = s.onreadystatechange = function() {
                                            if (!r && (!this.readyState || this.readyState === 'complete')) {
                                            r = true;
                                            callback.apply(args);
                                            }
                                            };
                                            };
                                            t = document.getElementsByTagName('script')[0];
                                            t.parent.insertBefore(s, t);
                                            }






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Jul 11 '13 at 19:18









                                            TiboTibo

                                            98079




                                            98079























                                                2














                                                Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.



                                                There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .



                                                After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.



                                                In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.



                                                Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:



                                                [
                                                'script1.js',
                                                'script2.js',
                                                'script3.js',
                                                'script4.js'
                                                ].forEach(function(src) {
                                                var script = document.createElement('script');
                                                script.src = src;
                                                script.async = false;
                                                document.head.appendChild(script);
                                                });


                                                Now, Spec says: Download together, execute in order as soon as all download.



                                                Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.



                                                Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.



                                                IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.



                                                Everything else says: I’m your friend, we’re going to do this by the book.



                                                Now, the full code with IE < 10 workaround:



                                                var scripts = [
                                                'script1.js',
                                                'script2.js',
                                                'script3.js',
                                                'script4.js'
                                                ];
                                                var src;
                                                var script;
                                                var pendingScripts = ;
                                                var firstScript = document.scripts[0];

                                                // Watch scripts load in IE
                                                function stateChange() {
                                                // Execute as many scripts in order as we can
                                                var pendingScript;
                                                while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
                                                pendingScript = pendingScripts.shift();
                                                // avoid future loading events from this script (eg, if src changes)
                                                pendingScript.onreadystatechange = null;
                                                // can't just appendChild, old IE bug if element isn't closed
                                                firstScript.parentNode.insertBefore(pendingScript, firstScript);
                                                }
                                                }

                                                // loop through our script urls
                                                while (src = scripts.shift()) {
                                                if ('async' in firstScript) { // modern browsers
                                                script = document.createElement('script');
                                                script.async = false;
                                                script.src = src;
                                                document.head.appendChild(script);
                                                }
                                                else if (firstScript.readyState) { // IE<10
                                                // create a script and add it to our todo pile
                                                script = document.createElement('script');
                                                pendingScripts.push(script);
                                                // listen for state changes
                                                script.onreadystatechange = stateChange;
                                                // must set src AFTER adding onreadystatechange listener
                                                // else we’ll miss the loaded event for cached scripts
                                                script.src = src;
                                                }
                                                else { // fall back to defer
                                                document.write('<script src="' + src + '" defer></'+'script>');
                                                }
                                                }





                                                share|improve this answer




























                                                  2














                                                  Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.



                                                  There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .



                                                  After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.



                                                  In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.



                                                  Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:



                                                  [
                                                  'script1.js',
                                                  'script2.js',
                                                  'script3.js',
                                                  'script4.js'
                                                  ].forEach(function(src) {
                                                  var script = document.createElement('script');
                                                  script.src = src;
                                                  script.async = false;
                                                  document.head.appendChild(script);
                                                  });


                                                  Now, Spec says: Download together, execute in order as soon as all download.



                                                  Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.



                                                  Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.



                                                  IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.



                                                  Everything else says: I’m your friend, we’re going to do this by the book.



                                                  Now, the full code with IE < 10 workaround:



                                                  var scripts = [
                                                  'script1.js',
                                                  'script2.js',
                                                  'script3.js',
                                                  'script4.js'
                                                  ];
                                                  var src;
                                                  var script;
                                                  var pendingScripts = ;
                                                  var firstScript = document.scripts[0];

                                                  // Watch scripts load in IE
                                                  function stateChange() {
                                                  // Execute as many scripts in order as we can
                                                  var pendingScript;
                                                  while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
                                                  pendingScript = pendingScripts.shift();
                                                  // avoid future loading events from this script (eg, if src changes)
                                                  pendingScript.onreadystatechange = null;
                                                  // can't just appendChild, old IE bug if element isn't closed
                                                  firstScript.parentNode.insertBefore(pendingScript, firstScript);
                                                  }
                                                  }

                                                  // loop through our script urls
                                                  while (src = scripts.shift()) {
                                                  if ('async' in firstScript) { // modern browsers
                                                  script = document.createElement('script');
                                                  script.async = false;
                                                  script.src = src;
                                                  document.head.appendChild(script);
                                                  }
                                                  else if (firstScript.readyState) { // IE<10
                                                  // create a script and add it to our todo pile
                                                  script = document.createElement('script');
                                                  pendingScripts.push(script);
                                                  // listen for state changes
                                                  script.onreadystatechange = stateChange;
                                                  // must set src AFTER adding onreadystatechange listener
                                                  // else we’ll miss the loaded event for cached scripts
                                                  script.src = src;
                                                  }
                                                  else { // fall back to defer
                                                  document.write('<script src="' + src + '" defer></'+'script>');
                                                  }
                                                  }





                                                  share|improve this answer


























                                                    2












                                                    2








                                                    2







                                                    Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.



                                                    There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .



                                                    After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.



                                                    In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.



                                                    Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:



                                                    [
                                                    'script1.js',
                                                    'script2.js',
                                                    'script3.js',
                                                    'script4.js'
                                                    ].forEach(function(src) {
                                                    var script = document.createElement('script');
                                                    script.src = src;
                                                    script.async = false;
                                                    document.head.appendChild(script);
                                                    });


                                                    Now, Spec says: Download together, execute in order as soon as all download.



                                                    Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.



                                                    Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.



                                                    IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.



                                                    Everything else says: I’m your friend, we’re going to do this by the book.



                                                    Now, the full code with IE < 10 workaround:



                                                    var scripts = [
                                                    'script1.js',
                                                    'script2.js',
                                                    'script3.js',
                                                    'script4.js'
                                                    ];
                                                    var src;
                                                    var script;
                                                    var pendingScripts = ;
                                                    var firstScript = document.scripts[0];

                                                    // Watch scripts load in IE
                                                    function stateChange() {
                                                    // Execute as many scripts in order as we can
                                                    var pendingScript;
                                                    while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
                                                    pendingScript = pendingScripts.shift();
                                                    // avoid future loading events from this script (eg, if src changes)
                                                    pendingScript.onreadystatechange = null;
                                                    // can't just appendChild, old IE bug if element isn't closed
                                                    firstScript.parentNode.insertBefore(pendingScript, firstScript);
                                                    }
                                                    }

                                                    // loop through our script urls
                                                    while (src = scripts.shift()) {
                                                    if ('async' in firstScript) { // modern browsers
                                                    script = document.createElement('script');
                                                    script.async = false;
                                                    script.src = src;
                                                    document.head.appendChild(script);
                                                    }
                                                    else if (firstScript.readyState) { // IE<10
                                                    // create a script and add it to our todo pile
                                                    script = document.createElement('script');
                                                    pendingScripts.push(script);
                                                    // listen for state changes
                                                    script.onreadystatechange = stateChange;
                                                    // must set src AFTER adding onreadystatechange listener
                                                    // else we’ll miss the loaded event for cached scripts
                                                    script.src = src;
                                                    }
                                                    else { // fall back to defer
                                                    document.write('<script src="' + src + '" defer></'+'script>');
                                                    }
                                                    }





                                                    share|improve this answer













                                                    Here is a great contemporary solution to the asynchronous script loading though it only address the js script with async false.



                                                    There is a great article written in www.html5rocks.com - Deep dive into the murky waters of script loading .



                                                    After considering many possible solutions, the author concluded that adding js scripts to the end of body element is the best possible way to avoid blocking page rendering by js scripts.



                                                    In the mean time, the author added another good alternate solution for those people who are desperate to load and execute scripts asynchronously.



                                                    Considering you've four scripts named script1.js, script2.js, script3.js, script4.js then you can do it with applying async = false:



                                                    [
                                                    'script1.js',
                                                    'script2.js',
                                                    'script3.js',
                                                    'script4.js'
                                                    ].forEach(function(src) {
                                                    var script = document.createElement('script');
                                                    script.src = src;
                                                    script.async = false;
                                                    document.head.appendChild(script);
                                                    });


                                                    Now, Spec says: Download together, execute in order as soon as all download.



                                                    Firefox < 3.6, Opera says: I have no idea what this “async” thing is, but it just so happens I execute scripts added via JS in the order they’re added.



                                                    Safari 5.0 says: I understand “async”, but don’t understand setting it to “false” with JS. I’ll execute your scripts as soon as they land, in whatever order.



                                                    IE < 10 says: No idea about “async”, but there is a workaround using “onreadystatechange”.



                                                    Everything else says: I’m your friend, we’re going to do this by the book.



                                                    Now, the full code with IE < 10 workaround:



                                                    var scripts = [
                                                    'script1.js',
                                                    'script2.js',
                                                    'script3.js',
                                                    'script4.js'
                                                    ];
                                                    var src;
                                                    var script;
                                                    var pendingScripts = ;
                                                    var firstScript = document.scripts[0];

                                                    // Watch scripts load in IE
                                                    function stateChange() {
                                                    // Execute as many scripts in order as we can
                                                    var pendingScript;
                                                    while (pendingScripts[0] && ( pendingScripts[0].readyState == 'loaded' || pendingScripts[0].readyState == 'complete' ) ) {
                                                    pendingScript = pendingScripts.shift();
                                                    // avoid future loading events from this script (eg, if src changes)
                                                    pendingScript.onreadystatechange = null;
                                                    // can't just appendChild, old IE bug if element isn't closed
                                                    firstScript.parentNode.insertBefore(pendingScript, firstScript);
                                                    }
                                                    }

                                                    // loop through our script urls
                                                    while (src = scripts.shift()) {
                                                    if ('async' in firstScript) { // modern browsers
                                                    script = document.createElement('script');
                                                    script.async = false;
                                                    script.src = src;
                                                    document.head.appendChild(script);
                                                    }
                                                    else if (firstScript.readyState) { // IE<10
                                                    // create a script and add it to our todo pile
                                                    script = document.createElement('script');
                                                    pendingScripts.push(script);
                                                    // listen for state changes
                                                    script.onreadystatechange = stateChange;
                                                    // must set src AFTER adding onreadystatechange listener
                                                    // else we’ll miss the loaded event for cached scripts
                                                    script.src = src;
                                                    }
                                                    else { // fall back to defer
                                                    document.write('<script src="' + src + '" defer></'+'script>');
                                                    }
                                                    }






                                                    share|improve this answer












                                                    share|improve this answer



                                                    share|improve this answer










                                                    answered Aug 3 '17 at 16:45









                                                    asmmahmudasmmahmud

                                                    2,4411828




                                                    2,4411828























                                                        1














                                                        One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:



                                                        callMyFunctions();


                                                        instead of:



                                                        $(window).load(function() {
                                                        callMyFunctions();
                                                        });


                                                        This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.



                                                        If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.






                                                        share|improve this answer




























                                                          1














                                                          One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:



                                                          callMyFunctions();


                                                          instead of:



                                                          $(window).load(function() {
                                                          callMyFunctions();
                                                          });


                                                          This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.



                                                          If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.






                                                          share|improve this answer


























                                                            1












                                                            1








                                                            1







                                                            One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:



                                                            callMyFunctions();


                                                            instead of:



                                                            $(window).load(function() {
                                                            callMyFunctions();
                                                            });


                                                            This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.



                                                            If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.






                                                            share|improve this answer













                                                            One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:



                                                            callMyFunctions();


                                                            instead of:



                                                            $(window).load(function() {
                                                            callMyFunctions();
                                                            });


                                                            This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.



                                                            If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Oct 10 '11 at 21:51









                                                            therintherin

                                                            1,08011127




                                                            1,08011127























                                                                1














                                                                I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.



                                                                Here is an example of loading jquery:



                                                                Modernizr.load([
                                                                {
                                                                load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
                                                                complete: function () {
                                                                if ( !window.jQuery ) {
                                                                Modernizr.load('js/libs/jquery-1.6.1.min.js');
                                                                }
                                                                }
                                                                },
                                                                {
                                                                // This will wait for the fallback to load and
                                                                // execute if it needs to.
                                                                load: 'needs-jQuery.js'
                                                                }
                                                                ]);





                                                                share|improve this answer




























                                                                  1














                                                                  I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.



                                                                  Here is an example of loading jquery:



                                                                  Modernizr.load([
                                                                  {
                                                                  load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
                                                                  complete: function () {
                                                                  if ( !window.jQuery ) {
                                                                  Modernizr.load('js/libs/jquery-1.6.1.min.js');
                                                                  }
                                                                  }
                                                                  },
                                                                  {
                                                                  // This will wait for the fallback to load and
                                                                  // execute if it needs to.
                                                                  load: 'needs-jQuery.js'
                                                                  }
                                                                  ]);





                                                                  share|improve this answer


























                                                                    1












                                                                    1








                                                                    1







                                                                    I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.



                                                                    Here is an example of loading jquery:



                                                                    Modernizr.load([
                                                                    {
                                                                    load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
                                                                    complete: function () {
                                                                    if ( !window.jQuery ) {
                                                                    Modernizr.load('js/libs/jquery-1.6.1.min.js');
                                                                    }
                                                                    }
                                                                    },
                                                                    {
                                                                    // This will wait for the fallback to load and
                                                                    // execute if it needs to.
                                                                    load: 'needs-jQuery.js'
                                                                    }
                                                                    ]);





                                                                    share|improve this answer













                                                                    I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.



                                                                    Here is an example of loading jquery:



                                                                    Modernizr.load([
                                                                    {
                                                                    load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
                                                                    complete: function () {
                                                                    if ( !window.jQuery ) {
                                                                    Modernizr.load('js/libs/jquery-1.6.1.min.js');
                                                                    }
                                                                    }
                                                                    },
                                                                    {
                                                                    // This will wait for the fallback to load and
                                                                    // execute if it needs to.
                                                                    load: 'needs-jQuery.js'
                                                                    }
                                                                    ]);






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Oct 10 '11 at 22:10









                                                                    Shawn McleanShawn Mclean

                                                                    29k81254384




                                                                    29k81254384























                                                                        1














                                                                        I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.



                                                                        export default class ScriptLoader {
                                                                        constructor (options) {
                                                                        const { src, global, protocol = document.location.protocol } = options
                                                                        this.src = src
                                                                        this.global = global
                                                                        this.protocol = protocol
                                                                        this.isLoaded = false
                                                                        }

                                                                        loadScript () {
                                                                        return new Promise((resolve, reject) => {
                                                                        // Create script element and set attributes
                                                                        const script = document.createElement('script')
                                                                        script.type = 'text/javascript'
                                                                        script.async = true
                                                                        script.src = `${this.protocol}//${this.src}`

                                                                        // Append the script to the DOM
                                                                        const el = document.getElementsByTagName('script')[0]
                                                                        el.parentNode.insertBefore(script, el)

                                                                        // Resolve the promise once the script is loaded
                                                                        script.addEventListener('load', () => {
                                                                        this.isLoaded = true
                                                                        resolve(script)
                                                                        })

                                                                        // Catch any errors while loading the script
                                                                        script.addEventListener('error', () => {
                                                                        reject(new Error(`${this.src} failed to load.`))
                                                                        })
                                                                        })
                                                                        }

                                                                        load () {
                                                                        return new Promise(async (resolve, reject) => {
                                                                        if (!this.isLoaded) {
                                                                        try {
                                                                        await this.loadScript()
                                                                        resolve(window[this.global])
                                                                        } catch (e) {
                                                                        reject(e)
                                                                        }
                                                                        } else {
                                                                        resolve(window[this.global])
                                                                        }
                                                                        })
                                                                        }
                                                                        }


                                                                        Usage is like this:



                                                                        const loader = new Loader({
                                                                        src: 'cdn.segment.com/analytics.js',
                                                                        global: 'Segment',
                                                                        })

                                                                        // scriptToLoad will now be a reference to `window.Segment`
                                                                        const scriptToLoad = await loader.load()





                                                                        share|improve this answer




























                                                                          1














                                                                          I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.



                                                                          export default class ScriptLoader {
                                                                          constructor (options) {
                                                                          const { src, global, protocol = document.location.protocol } = options
                                                                          this.src = src
                                                                          this.global = global
                                                                          this.protocol = protocol
                                                                          this.isLoaded = false
                                                                          }

                                                                          loadScript () {
                                                                          return new Promise((resolve, reject) => {
                                                                          // Create script element and set attributes
                                                                          const script = document.createElement('script')
                                                                          script.type = 'text/javascript'
                                                                          script.async = true
                                                                          script.src = `${this.protocol}//${this.src}`

                                                                          // Append the script to the DOM
                                                                          const el = document.getElementsByTagName('script')[0]
                                                                          el.parentNode.insertBefore(script, el)

                                                                          // Resolve the promise once the script is loaded
                                                                          script.addEventListener('load', () => {
                                                                          this.isLoaded = true
                                                                          resolve(script)
                                                                          })

                                                                          // Catch any errors while loading the script
                                                                          script.addEventListener('error', () => {
                                                                          reject(new Error(`${this.src} failed to load.`))
                                                                          })
                                                                          })
                                                                          }

                                                                          load () {
                                                                          return new Promise(async (resolve, reject) => {
                                                                          if (!this.isLoaded) {
                                                                          try {
                                                                          await this.loadScript()
                                                                          resolve(window[this.global])
                                                                          } catch (e) {
                                                                          reject(e)
                                                                          }
                                                                          } else {
                                                                          resolve(window[this.global])
                                                                          }
                                                                          })
                                                                          }
                                                                          }


                                                                          Usage is like this:



                                                                          const loader = new Loader({
                                                                          src: 'cdn.segment.com/analytics.js',
                                                                          global: 'Segment',
                                                                          })

                                                                          // scriptToLoad will now be a reference to `window.Segment`
                                                                          const scriptToLoad = await loader.load()





                                                                          share|improve this answer


























                                                                            1












                                                                            1








                                                                            1







                                                                            I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.



                                                                            export default class ScriptLoader {
                                                                            constructor (options) {
                                                                            const { src, global, protocol = document.location.protocol } = options
                                                                            this.src = src
                                                                            this.global = global
                                                                            this.protocol = protocol
                                                                            this.isLoaded = false
                                                                            }

                                                                            loadScript () {
                                                                            return new Promise((resolve, reject) => {
                                                                            // Create script element and set attributes
                                                                            const script = document.createElement('script')
                                                                            script.type = 'text/javascript'
                                                                            script.async = true
                                                                            script.src = `${this.protocol}//${this.src}`

                                                                            // Append the script to the DOM
                                                                            const el = document.getElementsByTagName('script')[0]
                                                                            el.parentNode.insertBefore(script, el)

                                                                            // Resolve the promise once the script is loaded
                                                                            script.addEventListener('load', () => {
                                                                            this.isLoaded = true
                                                                            resolve(script)
                                                                            })

                                                                            // Catch any errors while loading the script
                                                                            script.addEventListener('error', () => {
                                                                            reject(new Error(`${this.src} failed to load.`))
                                                                            })
                                                                            })
                                                                            }

                                                                            load () {
                                                                            return new Promise(async (resolve, reject) => {
                                                                            if (!this.isLoaded) {
                                                                            try {
                                                                            await this.loadScript()
                                                                            resolve(window[this.global])
                                                                            } catch (e) {
                                                                            reject(e)
                                                                            }
                                                                            } else {
                                                                            resolve(window[this.global])
                                                                            }
                                                                            })
                                                                            }
                                                                            }


                                                                            Usage is like this:



                                                                            const loader = new Loader({
                                                                            src: 'cdn.segment.com/analytics.js',
                                                                            global: 'Segment',
                                                                            })

                                                                            // scriptToLoad will now be a reference to `window.Segment`
                                                                            const scriptToLoad = await loader.load()





                                                                            share|improve this answer













                                                                            I wrote a little post to help out with this, you can read more here https://timber.io/snippets/asynchronously-load-a-script-in-the-browser-with-javascript/, but I've attached the helper class below. It will automatically wait for a script to load and return a specified window attribute once it does.



                                                                            export default class ScriptLoader {
                                                                            constructor (options) {
                                                                            const { src, global, protocol = document.location.protocol } = options
                                                                            this.src = src
                                                                            this.global = global
                                                                            this.protocol = protocol
                                                                            this.isLoaded = false
                                                                            }

                                                                            loadScript () {
                                                                            return new Promise((resolve, reject) => {
                                                                            // Create script element and set attributes
                                                                            const script = document.createElement('script')
                                                                            script.type = 'text/javascript'
                                                                            script.async = true
                                                                            script.src = `${this.protocol}//${this.src}`

                                                                            // Append the script to the DOM
                                                                            const el = document.getElementsByTagName('script')[0]
                                                                            el.parentNode.insertBefore(script, el)

                                                                            // Resolve the promise once the script is loaded
                                                                            script.addEventListener('load', () => {
                                                                            this.isLoaded = true
                                                                            resolve(script)
                                                                            })

                                                                            // Catch any errors while loading the script
                                                                            script.addEventListener('error', () => {
                                                                            reject(new Error(`${this.src} failed to load.`))
                                                                            })
                                                                            })
                                                                            }

                                                                            load () {
                                                                            return new Promise(async (resolve, reject) => {
                                                                            if (!this.isLoaded) {
                                                                            try {
                                                                            await this.loadScript()
                                                                            resolve(window[this.global])
                                                                            } catch (e) {
                                                                            reject(e)
                                                                            }
                                                                            } else {
                                                                            resolve(window[this.global])
                                                                            }
                                                                            })
                                                                            }
                                                                            }


                                                                            Usage is like this:



                                                                            const loader = new Loader({
                                                                            src: 'cdn.segment.com/analytics.js',
                                                                            global: 'Segment',
                                                                            })

                                                                            // scriptToLoad will now be a reference to `window.Segment`
                                                                            const scriptToLoad = await loader.load()






                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered May 4 '18 at 14:49









                                                                            ZachZach

                                                                            1,0231119




                                                                            1,0231119























                                                                                1














                                                                                You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript



                                                                                It explains how and when to use such technique.






                                                                                share|improve this answer


























                                                                                • Unfortunately, the link appears to be dead. :(

                                                                                  – Eric Seastrand
                                                                                  Dec 4 '17 at 20:28











                                                                                • @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                  – tereško
                                                                                  Dec 4 '17 at 20:31
















                                                                                1














                                                                                You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript



                                                                                It explains how and when to use such technique.






                                                                                share|improve this answer


























                                                                                • Unfortunately, the link appears to be dead. :(

                                                                                  – Eric Seastrand
                                                                                  Dec 4 '17 at 20:28











                                                                                • @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                  – tereško
                                                                                  Dec 4 '17 at 20:31














                                                                                1












                                                                                1








                                                                                1







                                                                                You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript



                                                                                It explains how and when to use such technique.






                                                                                share|improve this answer















                                                                                You might find this wiki article interesting : http://ajaxpatterns.org/On-Demand_Javascript



                                                                                It explains how and when to use such technique.







                                                                                share|improve this answer














                                                                                share|improve this answer



                                                                                share|improve this answer








                                                                                edited Nov 23 '18 at 20:16









                                                                                Joel Ellis

                                                                                315116




                                                                                315116










                                                                                answered Oct 10 '11 at 21:38









                                                                                tereškotereško

                                                                                52.7k2178136




                                                                                52.7k2178136













                                                                                • Unfortunately, the link appears to be dead. :(

                                                                                  – Eric Seastrand
                                                                                  Dec 4 '17 at 20:28











                                                                                • @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                  – tereško
                                                                                  Dec 4 '17 at 20:31



















                                                                                • Unfortunately, the link appears to be dead. :(

                                                                                  – Eric Seastrand
                                                                                  Dec 4 '17 at 20:28











                                                                                • @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                  – tereško
                                                                                  Dec 4 '17 at 20:31

















                                                                                Unfortunately, the link appears to be dead. :(

                                                                                – Eric Seastrand
                                                                                Dec 4 '17 at 20:28





                                                                                Unfortunately, the link appears to be dead. :(

                                                                                – Eric Seastrand
                                                                                Dec 4 '17 at 20:28













                                                                                @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                – tereško
                                                                                Dec 4 '17 at 20:31





                                                                                @Eric it's because that is an ancient method of dynamically loading code :D

                                                                                – tereško
                                                                                Dec 4 '17 at 20:31











                                                                                0














                                                                                Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.



                                                                                Try x.parentNode.appendChild() instead.






                                                                                share|improve this answer




























                                                                                  0














                                                                                  Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.



                                                                                  Try x.parentNode.appendChild() instead.






                                                                                  share|improve this answer


























                                                                                    0












                                                                                    0








                                                                                    0







                                                                                    Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.



                                                                                    Try x.parentNode.appendChild() instead.






                                                                                    share|improve this answer













                                                                                    Well, x.parentNode returns the HEAD element, so you are inserting the script just before the head tag. Maybe that's the problem.



                                                                                    Try x.parentNode.appendChild() instead.







                                                                                    share|improve this answer












                                                                                    share|improve this answer



                                                                                    share|improve this answer










                                                                                    answered Oct 10 '11 at 21:45









                                                                                    alekopalekop

                                                                                    1,60211734




                                                                                    1,60211734























                                                                                        0














                                                                                        Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.






                                                                                        share|improve this answer



















                                                                                        • 1





                                                                                          Needs jquery...

                                                                                          – Abram
                                                                                          Mar 7 '16 at 22:23











                                                                                        • It's possible to change it a little to get rid of jquery dependency

                                                                                          – Stephen L.
                                                                                          Mar 29 '16 at 7:26
















                                                                                        0














                                                                                        Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.






                                                                                        share|improve this answer



















                                                                                        • 1





                                                                                          Needs jquery...

                                                                                          – Abram
                                                                                          Mar 7 '16 at 22:23











                                                                                        • It's possible to change it a little to get rid of jquery dependency

                                                                                          – Stephen L.
                                                                                          Mar 29 '16 at 7:26














                                                                                        0












                                                                                        0








                                                                                        0







                                                                                        Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.






                                                                                        share|improve this answer













                                                                                        Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Mar 5 '15 at 21:50









                                                                                        Stephen L.Stephen L.

                                                                                        344111




                                                                                        344111








                                                                                        • 1





                                                                                          Needs jquery...

                                                                                          – Abram
                                                                                          Mar 7 '16 at 22:23











                                                                                        • It's possible to change it a little to get rid of jquery dependency

                                                                                          – Stephen L.
                                                                                          Mar 29 '16 at 7:26














                                                                                        • 1





                                                                                          Needs jquery...

                                                                                          – Abram
                                                                                          Mar 7 '16 at 22:23











                                                                                        • It's possible to change it a little to get rid of jquery dependency

                                                                                          – Stephen L.
                                                                                          Mar 29 '16 at 7:26








                                                                                        1




                                                                                        1





                                                                                        Needs jquery...

                                                                                        – Abram
                                                                                        Mar 7 '16 at 22:23





                                                                                        Needs jquery...

                                                                                        – Abram
                                                                                        Mar 7 '16 at 22:23













                                                                                        It's possible to change it a little to get rid of jquery dependency

                                                                                        – Stephen L.
                                                                                        Mar 29 '16 at 7:26





                                                                                        It's possible to change it a little to get rid of jquery dependency

                                                                                        – Stephen L.
                                                                                        Mar 29 '16 at 7:26











                                                                                        0














                                                                                        You can use LABJS or RequreJS



                                                                                        Script loaders like LABJS, RequireJS will improve the speed and quality of your code.






                                                                                        share|improve this answer






























                                                                                          0














                                                                                          You can use LABJS or RequreJS



                                                                                          Script loaders like LABJS, RequireJS will improve the speed and quality of your code.






                                                                                          share|improve this answer




























                                                                                            0












                                                                                            0








                                                                                            0







                                                                                            You can use LABJS or RequreJS



                                                                                            Script loaders like LABJS, RequireJS will improve the speed and quality of your code.






                                                                                            share|improve this answer















                                                                                            You can use LABJS or RequreJS



                                                                                            Script loaders like LABJS, RequireJS will improve the speed and quality of your code.







                                                                                            share|improve this answer














                                                                                            share|improve this answer



                                                                                            share|improve this answer








                                                                                            edited Apr 29 '15 at 5:53









                                                                                            shA.t

                                                                                            13.1k43871




                                                                                            13.1k43871










                                                                                            answered Apr 29 '15 at 5:49









                                                                                            KaushikKaushik

                                                                                            595




                                                                                            595























                                                                                                0














                                                                                                Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:



                                                                                                fetcInject([
                                                                                                'js/jquery-1.6.2.min.js',
                                                                                                'js/marquee.js',
                                                                                                'css/marquee.css',
                                                                                                'css/custom-theme/jquery-ui-1.8.16.custom.css',
                                                                                                'css/main.css'
                                                                                                ]).then(() => {
                                                                                                'js/jquery-ui-1.8.16.custom.min.js',
                                                                                                'js/farinspace/jquery.imgpreload.min.js'
                                                                                                })


                                                                                                For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write.






                                                                                                share|improve this answer




























                                                                                                  0














                                                                                                  Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:



                                                                                                  fetcInject([
                                                                                                  'js/jquery-1.6.2.min.js',
                                                                                                  'js/marquee.js',
                                                                                                  'css/marquee.css',
                                                                                                  'css/custom-theme/jquery-ui-1.8.16.custom.css',
                                                                                                  'css/main.css'
                                                                                                  ]).then(() => {
                                                                                                  'js/jquery-ui-1.8.16.custom.min.js',
                                                                                                  'js/farinspace/jquery.imgpreload.min.js'
                                                                                                  })


                                                                                                  For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write.






                                                                                                  share|improve this answer


























                                                                                                    0












                                                                                                    0








                                                                                                    0







                                                                                                    Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:



                                                                                                    fetcInject([
                                                                                                    'js/jquery-1.6.2.min.js',
                                                                                                    'js/marquee.js',
                                                                                                    'css/marquee.css',
                                                                                                    'css/custom-theme/jquery-ui-1.8.16.custom.css',
                                                                                                    'css/main.css'
                                                                                                    ]).then(() => {
                                                                                                    'js/jquery-ui-1.8.16.custom.min.js',
                                                                                                    'js/farinspace/jquery.imgpreload.min.js'
                                                                                                    })


                                                                                                    For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write.






                                                                                                    share|improve this answer













                                                                                                    Have you considered using Fetch Injection? I rolled an open source library called fetch-inject to handle cases like these. Here's what your loader might look like using the lib:



                                                                                                    fetcInject([
                                                                                                    'js/jquery-1.6.2.min.js',
                                                                                                    'js/marquee.js',
                                                                                                    'css/marquee.css',
                                                                                                    'css/custom-theme/jquery-ui-1.8.16.custom.css',
                                                                                                    'css/main.css'
                                                                                                    ]).then(() => {
                                                                                                    'js/jquery-ui-1.8.16.custom.min.js',
                                                                                                    'js/farinspace/jquery.imgpreload.min.js'
                                                                                                    })


                                                                                                    For backwards compatibility leverage feature detection and fall-back to XHR Injection or Script DOM Elements, or simply inline the tags into the page using document.write.







                                                                                                    share|improve this answer












                                                                                                    share|improve this answer



                                                                                                    share|improve this answer










                                                                                                    answered Mar 15 '17 at 8:53









                                                                                                    Josh HabdasJosh Habdas

                                                                                                    3,2092734




                                                                                                    3,2092734























                                                                                                        0














                                                                                                        Here is my custom solution to eliminate render-blocking JavaScript:



                                                                                                        // put all your JS files here, in correct order
                                                                                                        const libs = {
                                                                                                        "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
                                                                                                        "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
                                                                                                        "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
                                                                                                        "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
                                                                                                        }
                                                                                                        const loadedLibs = {}
                                                                                                        let counter = 0

                                                                                                        const loadAsync = function(lib) {
                                                                                                        var http = new XMLHttpRequest()
                                                                                                        http.open("GET", libs[lib], true)
                                                                                                        http.onload = () => {
                                                                                                        loadedLibs[lib] = http.responseText
                                                                                                        if (++counter == Object.keys(libs).length) startScripts()
                                                                                                        }
                                                                                                        http.send()
                                                                                                        }

                                                                                                        const startScripts = function() {
                                                                                                        for (var lib in libs) eval(loadedLibs[lib])
                                                                                                        console.log("allLoaded")
                                                                                                        }

                                                                                                        for (var lib in libs) loadAsync(lib)


                                                                                                        In short, it loads all your scripts asynchronously, and then executes them consequently.



                                                                                                        Github repo: https://github.com/mudroljub/js-async-loader






                                                                                                        share|improve this answer





















                                                                                                        • 1





                                                                                                          Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                          – Abram
                                                                                                          Mar 7 '16 at 22:22






                                                                                                        • 1





                                                                                                          That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                          – Damjan Pavlica
                                                                                                          Dec 21 '17 at 22:59
















                                                                                                        0














                                                                                                        Here is my custom solution to eliminate render-blocking JavaScript:



                                                                                                        // put all your JS files here, in correct order
                                                                                                        const libs = {
                                                                                                        "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
                                                                                                        "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
                                                                                                        "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
                                                                                                        "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
                                                                                                        }
                                                                                                        const loadedLibs = {}
                                                                                                        let counter = 0

                                                                                                        const loadAsync = function(lib) {
                                                                                                        var http = new XMLHttpRequest()
                                                                                                        http.open("GET", libs[lib], true)
                                                                                                        http.onload = () => {
                                                                                                        loadedLibs[lib] = http.responseText
                                                                                                        if (++counter == Object.keys(libs).length) startScripts()
                                                                                                        }
                                                                                                        http.send()
                                                                                                        }

                                                                                                        const startScripts = function() {
                                                                                                        for (var lib in libs) eval(loadedLibs[lib])
                                                                                                        console.log("allLoaded")
                                                                                                        }

                                                                                                        for (var lib in libs) loadAsync(lib)


                                                                                                        In short, it loads all your scripts asynchronously, and then executes them consequently.



                                                                                                        Github repo: https://github.com/mudroljub/js-async-loader






                                                                                                        share|improve this answer





















                                                                                                        • 1





                                                                                                          Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                          – Abram
                                                                                                          Mar 7 '16 at 22:22






                                                                                                        • 1





                                                                                                          That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                          – Damjan Pavlica
                                                                                                          Dec 21 '17 at 22:59














                                                                                                        0












                                                                                                        0








                                                                                                        0







                                                                                                        Here is my custom solution to eliminate render-blocking JavaScript:



                                                                                                        // put all your JS files here, in correct order
                                                                                                        const libs = {
                                                                                                        "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
                                                                                                        "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
                                                                                                        "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
                                                                                                        "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
                                                                                                        }
                                                                                                        const loadedLibs = {}
                                                                                                        let counter = 0

                                                                                                        const loadAsync = function(lib) {
                                                                                                        var http = new XMLHttpRequest()
                                                                                                        http.open("GET", libs[lib], true)
                                                                                                        http.onload = () => {
                                                                                                        loadedLibs[lib] = http.responseText
                                                                                                        if (++counter == Object.keys(libs).length) startScripts()
                                                                                                        }
                                                                                                        http.send()
                                                                                                        }

                                                                                                        const startScripts = function() {
                                                                                                        for (var lib in libs) eval(loadedLibs[lib])
                                                                                                        console.log("allLoaded")
                                                                                                        }

                                                                                                        for (var lib in libs) loadAsync(lib)


                                                                                                        In short, it loads all your scripts asynchronously, and then executes them consequently.



                                                                                                        Github repo: https://github.com/mudroljub/js-async-loader






                                                                                                        share|improve this answer















                                                                                                        Here is my custom solution to eliminate render-blocking JavaScript:



                                                                                                        // put all your JS files here, in correct order
                                                                                                        const libs = {
                                                                                                        "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
                                                                                                        "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
                                                                                                        "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
                                                                                                        "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
                                                                                                        }
                                                                                                        const loadedLibs = {}
                                                                                                        let counter = 0

                                                                                                        const loadAsync = function(lib) {
                                                                                                        var http = new XMLHttpRequest()
                                                                                                        http.open("GET", libs[lib], true)
                                                                                                        http.onload = () => {
                                                                                                        loadedLibs[lib] = http.responseText
                                                                                                        if (++counter == Object.keys(libs).length) startScripts()
                                                                                                        }
                                                                                                        http.send()
                                                                                                        }

                                                                                                        const startScripts = function() {
                                                                                                        for (var lib in libs) eval(loadedLibs[lib])
                                                                                                        console.log("allLoaded")
                                                                                                        }

                                                                                                        for (var lib in libs) loadAsync(lib)


                                                                                                        In short, it loads all your scripts asynchronously, and then executes them consequently.



                                                                                                        Github repo: https://github.com/mudroljub/js-async-loader







                                                                                                        share|improve this answer














                                                                                                        share|improve this answer



                                                                                                        share|improve this answer








                                                                                                        edited Dec 21 '17 at 23:04

























                                                                                                        answered Nov 26 '15 at 20:44









                                                                                                        Damjan PavlicaDamjan Pavlica

                                                                                                        10.2k53054




                                                                                                        10.2k53054








                                                                                                        • 1





                                                                                                          Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                          – Abram
                                                                                                          Mar 7 '16 at 22:22






                                                                                                        • 1





                                                                                                          That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                          – Damjan Pavlica
                                                                                                          Dec 21 '17 at 22:59














                                                                                                        • 1





                                                                                                          Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                          – Abram
                                                                                                          Mar 7 '16 at 22:22






                                                                                                        • 1





                                                                                                          That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                          – Damjan Pavlica
                                                                                                          Dec 21 '17 at 22:59








                                                                                                        1




                                                                                                        1





                                                                                                        Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                        – Abram
                                                                                                        Mar 7 '16 at 22:22





                                                                                                        Doesn't work No 'Access-Control-Allow-Origin' header is present on the requested resource

                                                                                                        – Abram
                                                                                                        Mar 7 '16 at 22:22




                                                                                                        1




                                                                                                        1





                                                                                                        That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                        – Damjan Pavlica
                                                                                                        Dec 21 '17 at 22:59





                                                                                                        That is CORS problem. stackoverflow.com/questions/20035101/…

                                                                                                        – Damjan Pavlica
                                                                                                        Dec 21 '17 at 22:59











                                                                                                        0














                                                                                                        Here a little ES6 function if somebody wants to use it in React for example






                                                                                                        import {uniqueId} from 'lodash' // optional
                                                                                                        /**
                                                                                                        * @param {String} file The path of the file you want to load.
                                                                                                        * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                        * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                        */
                                                                                                        export const loadAsyncScript = (file, callback, id) => {
                                                                                                        const d = document
                                                                                                        if (!id) { id = uniqueId('async_script') } // optional
                                                                                                        if (!d.getElementById(id)) {
                                                                                                        const tag = 'script'
                                                                                                        let newScript = d.createElement(tag)
                                                                                                        let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                        newScript.id = id
                                                                                                        newScript.async = true
                                                                                                        newScript.src = file
                                                                                                        if (callback) {
                                                                                                        // IE support
                                                                                                        newScript.onreadystatechange = () => {
                                                                                                        if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                        newScript.onreadystatechange = null
                                                                                                        callback(file)
                                                                                                        }
                                                                                                        }
                                                                                                        // Other (non-IE) browsers support
                                                                                                        newScript.onload = () => {
                                                                                                        callback(file)
                                                                                                        }
                                                                                                        }
                                                                                                        firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                        } else {
                                                                                                        console.error(`The script with id ${id} is already loaded`)
                                                                                                        }
                                                                                                        }








                                                                                                        share|improve this answer




























                                                                                                          0














                                                                                                          Here a little ES6 function if somebody wants to use it in React for example






                                                                                                          import {uniqueId} from 'lodash' // optional
                                                                                                          /**
                                                                                                          * @param {String} file The path of the file you want to load.
                                                                                                          * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                          * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                          */
                                                                                                          export const loadAsyncScript = (file, callback, id) => {
                                                                                                          const d = document
                                                                                                          if (!id) { id = uniqueId('async_script') } // optional
                                                                                                          if (!d.getElementById(id)) {
                                                                                                          const tag = 'script'
                                                                                                          let newScript = d.createElement(tag)
                                                                                                          let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                          newScript.id = id
                                                                                                          newScript.async = true
                                                                                                          newScript.src = file
                                                                                                          if (callback) {
                                                                                                          // IE support
                                                                                                          newScript.onreadystatechange = () => {
                                                                                                          if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                          newScript.onreadystatechange = null
                                                                                                          callback(file)
                                                                                                          }
                                                                                                          }
                                                                                                          // Other (non-IE) browsers support
                                                                                                          newScript.onload = () => {
                                                                                                          callback(file)
                                                                                                          }
                                                                                                          }
                                                                                                          firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                          } else {
                                                                                                          console.error(`The script with id ${id} is already loaded`)
                                                                                                          }
                                                                                                          }








                                                                                                          share|improve this answer


























                                                                                                            0












                                                                                                            0








                                                                                                            0







                                                                                                            Here a little ES6 function if somebody wants to use it in React for example






                                                                                                            import {uniqueId} from 'lodash' // optional
                                                                                                            /**
                                                                                                            * @param {String} file The path of the file you want to load.
                                                                                                            * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                            * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                            */
                                                                                                            export const loadAsyncScript = (file, callback, id) => {
                                                                                                            const d = document
                                                                                                            if (!id) { id = uniqueId('async_script') } // optional
                                                                                                            if (!d.getElementById(id)) {
                                                                                                            const tag = 'script'
                                                                                                            let newScript = d.createElement(tag)
                                                                                                            let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                            newScript.id = id
                                                                                                            newScript.async = true
                                                                                                            newScript.src = file
                                                                                                            if (callback) {
                                                                                                            // IE support
                                                                                                            newScript.onreadystatechange = () => {
                                                                                                            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                            newScript.onreadystatechange = null
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            // Other (non-IE) browsers support
                                                                                                            newScript.onload = () => {
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                            } else {
                                                                                                            console.error(`The script with id ${id} is already loaded`)
                                                                                                            }
                                                                                                            }








                                                                                                            share|improve this answer













                                                                                                            Here a little ES6 function if somebody wants to use it in React for example






                                                                                                            import {uniqueId} from 'lodash' // optional
                                                                                                            /**
                                                                                                            * @param {String} file The path of the file you want to load.
                                                                                                            * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                            * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                            */
                                                                                                            export const loadAsyncScript = (file, callback, id) => {
                                                                                                            const d = document
                                                                                                            if (!id) { id = uniqueId('async_script') } // optional
                                                                                                            if (!d.getElementById(id)) {
                                                                                                            const tag = 'script'
                                                                                                            let newScript = d.createElement(tag)
                                                                                                            let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                            newScript.id = id
                                                                                                            newScript.async = true
                                                                                                            newScript.src = file
                                                                                                            if (callback) {
                                                                                                            // IE support
                                                                                                            newScript.onreadystatechange = () => {
                                                                                                            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                            newScript.onreadystatechange = null
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            // Other (non-IE) browsers support
                                                                                                            newScript.onload = () => {
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                            } else {
                                                                                                            console.error(`The script with id ${id} is already loaded`)
                                                                                                            }
                                                                                                            }








                                                                                                            import {uniqueId} from 'lodash' // optional
                                                                                                            /**
                                                                                                            * @param {String} file The path of the file you want to load.
                                                                                                            * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                            * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                            */
                                                                                                            export const loadAsyncScript = (file, callback, id) => {
                                                                                                            const d = document
                                                                                                            if (!id) { id = uniqueId('async_script') } // optional
                                                                                                            if (!d.getElementById(id)) {
                                                                                                            const tag = 'script'
                                                                                                            let newScript = d.createElement(tag)
                                                                                                            let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                            newScript.id = id
                                                                                                            newScript.async = true
                                                                                                            newScript.src = file
                                                                                                            if (callback) {
                                                                                                            // IE support
                                                                                                            newScript.onreadystatechange = () => {
                                                                                                            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                            newScript.onreadystatechange = null
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            // Other (non-IE) browsers support
                                                                                                            newScript.onload = () => {
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                            } else {
                                                                                                            console.error(`The script with id ${id} is already loaded`)
                                                                                                            }
                                                                                                            }





                                                                                                            import {uniqueId} from 'lodash' // optional
                                                                                                            /**
                                                                                                            * @param {String} file The path of the file you want to load.
                                                                                                            * @param {Function} callback (optional) The function to call when the script loads.
                                                                                                            * @param {String} id (optional) The unique id of the file you want to load.
                                                                                                            */
                                                                                                            export const loadAsyncScript = (file, callback, id) => {
                                                                                                            const d = document
                                                                                                            if (!id) { id = uniqueId('async_script') } // optional
                                                                                                            if (!d.getElementById(id)) {
                                                                                                            const tag = 'script'
                                                                                                            let newScript = d.createElement(tag)
                                                                                                            let firstScript = d.getElementsByTagName(tag)[0]
                                                                                                            newScript.id = id
                                                                                                            newScript.async = true
                                                                                                            newScript.src = file
                                                                                                            if (callback) {
                                                                                                            // IE support
                                                                                                            newScript.onreadystatechange = () => {
                                                                                                            if (newScript.readyState === 'loaded' || newScript.readyState === 'complete') {
                                                                                                            newScript.onreadystatechange = null
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            // Other (non-IE) browsers support
                                                                                                            newScript.onload = () => {
                                                                                                            callback(file)
                                                                                                            }
                                                                                                            }
                                                                                                            firstScript.parentNode.insertBefore(newScript, firstScript)
                                                                                                            } else {
                                                                                                            console.error(`The script with id ${id} is already loaded`)
                                                                                                            }
                                                                                                            }






                                                                                                            share|improve this answer












                                                                                                            share|improve this answer



                                                                                                            share|improve this answer










                                                                                                            answered Aug 10 '18 at 1:56









                                                                                                            JoxieMedinaJoxieMedina

                                                                                                            6181912




                                                                                                            6181912























                                                                                                                -3














                                                                                                                I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.






                                                                                                                share|improve this answer




























                                                                                                                  -3














                                                                                                                  I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.






                                                                                                                  share|improve this answer


























                                                                                                                    -3












                                                                                                                    -3








                                                                                                                    -3







                                                                                                                    I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.






                                                                                                                    share|improve this answer













                                                                                                                    I would suggest looking into minifying the files first and see if that gives you a big enough speed boost. If your host is slow, could try putting that static content on a CDN.







                                                                                                                    share|improve this answer












                                                                                                                    share|improve this answer



                                                                                                                    share|improve this answer










                                                                                                                    answered Oct 10 '11 at 21:36









                                                                                                                    Jason MiesionczekJason Miesionczek

                                                                                                                    9,2831169107




                                                                                                                    9,2831169107






























                                                                                                                        draft saved

                                                                                                                        draft discarded




















































                                                                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                                                                        But avoid



                                                                                                                        • Asking for help, clarification, or responding to other answers.

                                                                                                                        • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                        To learn more, see our tips on writing great answers.




                                                                                                                        draft saved


                                                                                                                        draft discarded














                                                                                                                        StackExchange.ready(
                                                                                                                        function () {
                                                                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7718935%2fload-scripts-asynchronously%23new-answer', 'question_page');
                                                                                                                        }
                                                                                                                        );

                                                                                                                        Post as a guest















                                                                                                                        Required, but never shown





















































                                                                                                                        Required, but never shown














                                                                                                                        Required, but never shown












                                                                                                                        Required, but never shown







                                                                                                                        Required, but never shown

































                                                                                                                        Required, but never shown














                                                                                                                        Required, but never shown












                                                                                                                        Required, but never shown







                                                                                                                        Required, but never shown