Skip to content

Instantly share code, notes, and snippets.

@imlucas
Created December 28, 2009 20:43
Show Gist options
  • Select an option

  • Save imlucas/264927 to your computer and use it in GitHub Desktop.

Select an option

Save imlucas/264927 to your computer and use it in GitHub Desktop.
/**
* lucas' micro lazy loader.
*
* Super tiny lazy loader for external dependencies. Features callbacks when
* individual scripts are loaded and when all scripts have finished loading.
*
* @todo (lucas) Use interval to check for load errors
*
* $l(
* [
* 'http://plugins.jquery.com/files/labs_json.js_0.txt',
* [
* 'http://code.jquery.com/jquery-1.4a1.min.js',
* function(src){
* console.log('Loaded jquery 1.4 alpha 1 from '+src);
* }
* ]
* ],
* function(src_list){
* console.log('All sources loaded:');
* console.dir(src_list);
* alert('All sources loaded!');
* }
* );
*
* @author Lucas Hrabovsky http://www.imlucas.com http://www.twitter.com/__lucas
*/
var $l = function(r, cb){
var l = [],
u = undefined,
f = function(o){toString.call(o) === "[object Function]";},
a = function(o){toString.call(o) === "[object Array]";},
z = function(x){ // loads script with src=x. calls c when complete.
var d = document, s = d.createElement('script'), v = x, w = u;
if(a(x)){
v = x[0], w = x[1];
}
s.onload = s.onreadystatechange = function(){
var s = this;
if(!s.readyState||/de|te/.test(s.readyState)){
s.onload = s.onreadystatechange = null;
if(f(w)){
w.apply(this, v);
}
l.push(v);
if(l.length == r.length){
cb.apply(this, l);
}
}
};
s.src = v;
d.getElementsByTagName('head')[0].appendChild(s);
};
for(s in r){z(s);}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment