Skip to content

Instantly share code, notes, and snippets.

@Victa
Created September 5, 2012 08:34
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Victa/3633361 to your computer and use it in GitHub Desktop.
Save Victa/3633361 to your computer and use it in GitHub Desktop.
Asynchronous Script Loading
function asyncLoad(scriptURL,callback)
{
if(!scriptURL){return;}
var firstScriptTag=document.getElementsByTagName('script')[0];
var js=document.createElement('script');
js.type='text/javascript';
js.src=scriptURL;
js.async=true;
if(callback && typeof(callback)===typeof(Function))
{
//Modern browsers (IE9+)
if(js.addEventListener)
{
js.addEventListener('load',callback,false);
}
else//(IE8-)
{
js.onreadystatechange=function()
{
if(js.readyState in {loaded:1,complete:1})
{
js.onreadystatechange=null;
callback();
}
};
}
}
firstScriptTag.parentNode.insertBefore(js,firstScriptTag);
}
asyncLoad('some/local/script.js',someFunction);
function someFunction()
{
//script.js loaded
}
asyncLoad('http://code.jquery.com/jquery-1.8.0.min.js',function()
{
//$===jQuery
});
@Victa
Copy link
Author

Victa commented Sep 5, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment