asynchronous loading of css and javascript

Sometime back was pawing at async forEach in JavaScript that helped me to make a simple inject function that would help in loading CSS and JavaScript files to the HTML asynchronously!

Here is the code to load CSS and JavaScript Asynchronously :

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);
}

Usage:

require('jq.js');
 
require('jq.css');
 
require(['wiki.js','wiki.css']);

Share this