Shoora
5/22/2018 - 11:43 AM

pure js async script loader

pure js async script loader

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;
      if(callback) {
        callback();
      }
    }
  };
  
  t = document.getElementsByTagName('head')[0];
  t.appendChild(s);
}

/* Usage */
(function() {
  loadScript('the/path/to/your/script.js');
})();