Created
November 3, 2015 22:18
-
-
Save chriswburke/a326c4f021778faa2280 to your computer and use it in GitHub Desktop.
Async Loader
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
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