Skip to content

Instantly share code, notes, and snippets.

@chriswburke
Created November 3, 2015 22:18
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 chriswburke/a326c4f021778faa2280 to your computer and use it in GitHub Desktop.
Save chriswburke/a326c4f021778faa2280 to your computer and use it in GitHub Desktop.
Async Loader
var loader = {
script: function ( url ) {
var script = document.createElement( 'script' );
script.src = url;
return script;
},
css: function ( url ) {
var link = document.createElement( 'link' );
link.rel = "stylesheet";
link.type = "text/css";
link.href = url;
return link;
},
task: function ( url ) {
var item;
if ( /js$/.test( url ) ) item = loader.script( url );
if ( /css$/.test( url ) ) item = loader.css( url );
return new Promise( function ( resolve ) {
if ( !item ) {
console.log( url + " must be js or css" );
return resolve();
}
document.head.appendChild( item );
item.onload = resolve;
item.onerror = resolve;
} );
}
}
module.exports = function () {
var urls = [].slice.call( arguments );
return new Promise( function ( resolve ) {
function next() {
if ( !urls.length ) return resolve();
var url = urls.shift();
loader.task( url ).then( next );
}
next();
} );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment