---
title: "Asynchronous Loading of Css and Javascript"
description: "Sometime back was pawing at async forEach in JavaScript that helped me to make a simple inject function that would help in."
url: "https://h3manth.com/scribe/asynchronous-loading-css-and-javascript/"
canonical_url: "https://h3manth.com/scribe/asynchronous-loading-css-and-javascript/"
markdown_url: "https://h3manth.com/scribe/blog/asynchronous-loading-css-and-javascript.md"
publishDate: "2012-07-18T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript","web"]
word_count: 182
reading_time_minutes: 1
x_markdown_tokens: 529
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# 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.

Sometime back was pawing at [async forEach in JavaScript](http://h3manth.com/content/async-foreach-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']);
