Skip to content

Instantly share code, notes, and snippets.

@nikahmadz
Created October 18, 2017 03:20
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 nikahmadz/1fda9a92eca87d0c2f1df774e96cd878 to your computer and use it in GitHub Desktop.
Save nikahmadz/1fda9a92eca87d0c2f1df774e96cd878 to your computer and use it in GitHub Desktop.
GetScript: Inject external script to a document
/*
you'll need to include supporting script like: w,d,dm,i{},ti,to,wc
they are shortcuts for: window,document,DomJs,VariableTest,Timer,and console.
*/
var
gs=function(a){
if(!io(a)||!is(a.src)){we(': Invalid source: '+a.src);return}
var
b=a.callback,
v=a.valid,
ss='script',
sl='loaded';
if(im(b)&&r(v)){b(sl);return}
var
o={src:a.src},
s=dm.create(ss),
fa=function(v){
if(ib(a[v])||is(a[v])){o[v]=a[v]}
},
dn=!1,
fn,
ho,
hi,
x,
h=a.handle||d.scripts[0];
if(im(b)&&im(v)){
fn=function(){
if(dn){return}
dn=!0;
ti0(hi);
to0(ho);
b(v()?sl:'timeout');
};
ho=to1(fn,n(a.timeout,10000));
hi=ti1(function(){if(v()){fn();}},n(a.interval,1000));
if('readyState'in s){
s.onreadystatechange=function(){
if([sl,"complete"].indexOf(s.readyState)){
s.onreadystatechange=null;
fn();
}
};
}else{
s.onload=fn;
}
}
if(is(a.type)){o.type=a.type}
fa('defer');
fa('async');
for(x in o){dm.attr(s,x,o[x])}
dm.insertBefore(s,h);
};
// Usage Example
var
w=window,
ready=function(){
},
h=d.currentScript||d.scripts[0],
$v='3.2.1',
js='text/javascript',
sl='loaded',
cg=0
?'https://ajax.googleapis.com/ajax/libs/'
:'http://127.0.0.1:8887/';
gs({
src:cg+'jquery/'+$v+'/jquery.min.js',
type:js,
handle:h,
valid:function(){
return w.$ && w.$.fn && w.$.fn.jquery==$v
},
callback:function(s){
if(s!=sl){wt('JQ '+s);return}
$(ready);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment