Kategori arşivi: Javascript

Async script loading

Refs:

  • http://stackoverflow.com/questions/7718935/load-scripts-asynchronously
  • https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/

//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)