Created
September 5, 2012 08:34
-
-
Save Victa/3633361 to your computer and use it in GitHub Desktop.
Asynchronous Script Loading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
asyncLoad('some/local/script.js',someFunction); | |
function someFunction() | |
{ | |
//script.js loaded | |
} | |
asyncLoad('http://code.jquery.com/jquery-1.8.0.min.js',function() | |
{ | |
//$===jQuery | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source http://coderwall.com/p/2yacmq