Skip to content

Instantly share code, notes, and snippets.

@composite
Last active January 13, 2016 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save composite/3376806 to your computer and use it in GitHub Desktop.
Save composite/3376806 to your computer and use it in GitHub Desktop.
Micro DynamicScript Snippet
/*
by Composite (http://blog.hazard.kr)
reference -
http://stackoverflow.com/questions/4845762/onload-handler-for-script-tag-in-internet-explorer
Usage -
getScript('http://www.domain.com/js/myscript.js','utf-8').then(function(){
myMethod('yay!');
});
getScript('script1.js').then(fn1).getScript('script2.js').then(fn2)...
*/
function getScript(url,enc){
var head=document.getElementsByTagName('head')[0],script=document.createElement('script')
,_deff=function(){this.fn={};},done=false;
_deff.prototype.then=function(done){
if(typeof done === 'function') this.fn.done=done;
return {getScript:getScript};
};
var get=new _deff();
script.type="text/javascript";
if(enc) script.charset=enc;
script.onload=script.onreadystatechange=function(){
var rs=this.readyState;
if(done || (rs && rs !== "loaded" && rs !== "complete")) return;
done=true;
for(var x in get.fn) if(typeof get.fn[x] == 'function') get.fn[x].call(script);
script.onload = script.onreadystatechange = null;
if (head && script.parentNode) head.removeChild( script );
};
script.src=url;
head.insertBefore( script, head.firstChild );
return get;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment