Skip to content

Instantly share code, notes, and snippets.

@Ulv
Created November 1, 2013 10:54
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 Ulv/7263826 to your computer and use it in GitHub Desktop.
Save Ulv/7263826 to your computer and use it in GitHub Desktop.
async load css files. Usage: require('style.css');
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