RSS RSS feed | Atom Atom feed

Conditionally including javascript and css files

how to include/inject css or javascript on demand from within body of the docuement

Normally external javascript and css files are supposed to be included in the header of a web page. But, at times we come across situations when we need to include some javascript or css file when we are into the body of the page (that is head portion has already been written).

To include the javascript and css resources you can use the following two methods.


function injectJS (fileName, jsbase){
    var src = jsbase + '/' + fileName + '.js';
    var ipts = document.getElementsByTagName("script");
    var found = false;
    for (i=0; i < ipts.length; i++){
        var type = ipts[i].src;
        if (type.indexOf(fileName) != -1){
                    found = true;
        }
      }
     if (!found){
    var headID = document.getElementsByTagName("head")[0];        
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = src;
    headID.appendChild(newScript);           
    }
 }   
 
 
 function injectCSS (fileName, cssbase){
    var ipts = document.getElementsByTagName("link");
    var found = false;
    for (i=0; i < ipts.length; i++){
        if ( ipts[i].rel != 'stylesheet') continue;
        var type = ipts[i].href;
        if (type.indexOf(fileName) != -1){
                    found = true;
        }
      }
     if (!found){
        var headID = document.getElementsByTagName("head")[0];        
        var c = document.createElement('link');
        c.type = 'text/css';
        c.rel = 'stylesheet';
        c.href = cssbase + '/' + fileName + '.css';
        headID.appendChild(c);           
    }
 }   


Note that the fileName should not contain the .js or .css extension.
The methods can be called from anywhere in the body of the html page (from inside standard script tags/block).

Above methods make sure that the resource being injected is not included more than once. Feel free to use the code and modify it to suit your heart's content. No strings attached!


  



Add a comment Send a TrackBack



Legal Disclaimer | Privacy Statment