Created
November 1, 2013 10:54
-
-
Save Ulv/7263826 to your computer and use it in GitHub Desktop.
async load css files. Usage: require('style.css');
This file contains hidden or 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
function asyncInject(array, fn, delay) { | |
var i = 0; | |
window.setTimeout(function iter() { | |
if (i === array.length) { | |
return; | |
} | |
fn.call(array, array[i], i++); | |
window.setTimeout(iter, delay); | |
}, 0); | |
} | |
require = function (paths, callback) { | |
// Check if the path param is of the required type. | |
if (!paths instanceof Array || !paths instanceof String) { | |
console.log('Please check the useage'); | |
return; | |
} | |
// If paths param is a single param, convert it to an Array. | |
paths = typeof paths === 'string' ? paths.split() : paths | |
var js, css; | |
// For every path in paths add the required to the head. | |
asyncInject(paths, function (path) { | |
var type = path.split('.').pop(); | |
switch (type) { | |
case 'js': | |
js = document.createElement('script'); | |
js.src = path; | |
type = js; | |
break; | |
case 'css': | |
css = document.createElement('link'); | |
css.href = path; | |
css.rel = 'stylesheet'; | |
type = css; | |
break; | |
default: | |
return; | |
} | |
if (callback) | |
type.addEventListener('load', function (e) { | |
callback(e); | |
}, false); | |
document.head.appendChild(type); | |
}, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment