Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to add JavaScript and CSS files to a web page during runtime

0.00/5 (No votes)
10 May 2013 1  
How to add JavaScript and CSS files to a web page during runtime.

Introduction  

If you really want to load your website faster and want to have good ranking for your website in y-slow or etc.... Please look at the following process. These concepts developed by me and i also checked it in various ways, i will also give the sample code to test. If you are doing something, then please pause yourself for 10 min and go through these steps which will make any website faster and will give good y-slow ranking. 

If you really think at loading time of a website we need 20 to 30% or max 40% JavaScript of the application while the rest 60 to 70% we are loading at the time of page load without any reason. Same for CSS files too...  But if we will implement a concept in which we can load the required JavaScript and CSS at the time of load of the page and add the rest JavaScript or CSS files later if required - then we will catch our goal. 

How to do that

  • First: we have to split JavaScript and CSS files to number of files depending or different functionality.
  • Second: only add the required JavaScript and CSS files to your webpage
  • Third: Add required JavaScript and CSS files after page load on run time.

Using the code

Adding a JavaScript file dynamically:

var path    = "scriptFolder"
var script  = document.createElement( 'script' );
script.src  = path + '/jsFile.js';
document.getElementsByTagName( 'head' )[0].appendChild( script );

Adding a CSS file dynamically:

var path   = "css";
var style   = document.createElement( 'link' );
style.rel   = 'stylesheet';
style.type  = 'text/css';
style.href  = path + '/style.css';
document.getElementsByTagName( 'head' )[0].appendChild( style );

Example:

Here is a simple example and some steps to describe the whole functionality.

<div><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
  "<a href="http://www.w3.org/TR/html4/loose.dtd">
  http://www.w3.org/TR/html4/loose.dtd</a>">

Here I have taken two buttons ( name="check1" & name="check2" ) and two hidden divs ( id="box1" & id="box2")onclick of a button it will hide one and open one div , the div's has some classes defined in style.css file each div's has one one buttons and it has some onclick event which we are keeping in js1.js and js2.js files - If you will think slightly we do not need the js1.js and js2.js files on load If you see the page we only need the JavaScript onclick functions called showbox (boxid) at page load.

In Main.js:

var is_js1 = 0;
var is_js2 = 0;
var is_css1 = 0;
function showbox(id)
{
 if(id == 'box1')
 {
  
  //adding css
  if(is_css1 == 0)
  {
   var path  = "css";
   var style   = document.createElement( 'link' );
   style.rel   = 'stylesheet';
   style.type   = 'text/css';
   style.href   = path + '/style.css';
   document.getElementsByTagName( 'head' )[0].appendChild( style );
   is_css1 = 1;
  }   
  document.getElementById('box2').style.display='none';
  document.getElementById('box1').style.display='block';
  
  /***********Add JS**********/
  if(is_js1 == 0)
  {
   var path   = "javascripts"
   var script   = document.createElement( 'script' );
   //style.rel   = 'stylesheet';
   //style.type   = 'text/css';
   script.src   = path + '/js1.js';
   //style.media  = 'screen';
   document.getElementsByTagName( 'head' )[0].appendChild( script );
   is_js1 = 1;
  }     
 }
 else
 {
  //adding css
  if(is_css1 == 0)
  {
   var path  = "css";
   var style   = document.createElement( 'link' );
   style.rel   = 'stylesheet';
   style.type   = 'text/css';
   style.href   = path + '/style.css';
   document.getElementsByTagName( 'head' )[0].appendChild( style );
   is_css1 = 1;
  }   
  document.getElementById('box2').style.display='block';
  document.getElementById('box1').style.display='none';
  /***********Add JS**********/
  if(is_js2 == 0)
  {
   var path   = "javascripts"
   var script   = document.createElement( 'script' );
   //style.rel   = 'stylesheet';
   //style.type   = 'text/css';
   script.src   = path + '/js2.js';
   //style.media  = 'screen';
   document.getElementsByTagName( 'head' )[0].appendChild( script );
   is_js2 = 1;
  }    
 }
}

On page load we need this function here we are hiding and showing divs but here we are also adding CSS and JavaScript files. I took 3 Global variables to check whether a file already added or not, if added it will not add those files again to webpage.

function function1()
{
  alert("box1 function");
}

This is the js file holding the function for <input type="button" onClick="function2()" value="Box2 function2() call in (js2.js) file"> in Demo.html.

In the CSS file:

.myclass
{
border:2px solid #CC6600;width:400px; height:40px;
}
.myclass2
{
 width:400px; height:40px; border:3px solid green;
}

In this file we are keeping the class of box1 and box2 of index.html

Yet another way to load javascript asynchronously

  Most often we add a script file to an .aspx page by adding a script tag inside head element e.g.: <script  type="text/javascript" src="script/TestScript.js"></script>.

This method has a pitfall. Loading of the script file blocks the rendering of the page . (You can notice it in a low bandwidth network or if your JavaScript is too large). To avoid this problem, experienced programmers suggest to load the script at the end of the html document .

But lets explore some better method of loading JavaScript on to the page :


1. using DEFER: You can use 'defer' in script element to defer execution of a script block. Though, this is a part of HTML 4 specification, only IE4+ supports it correctly. Ex: <script defer="defer" type="text/javascript" src="script/TestScript.js">.

2. using AJAX: You can use to dynamically fetch the Javascript file and use it. Steps:

  1. Create a XMLHTTpRequest object
  2. Fetch the JavaScript file using AJAX
  3. EVAL() the result

Ex. 

// Create the XMLHttpRequest object
// This varies form browser to browser, so I leave it to you
 var ajaxObj = GetXHRObject();

// As usual set a call back handler and use eval() the result
ajaxObj.onreadystatechange = function() {
if (ajaxObj.readyState != 4 ) return;
    eval(ajaxObj.responseText);
};

ajaxObj.open('GET', 'script/TestScript.js', true);
ajaxObj .send('');

3. using document.Write() you can write a script inside the head element -

document.write("<script type="text/javascript" src="text/javascript">" + 
  "</script><span style="font-family: Courier New;"><script type='text/javascript' 
  src='text/javascript'>" + "</script></span>");

4. using script DOM element: Steps:
    1. Create a script element (of type script)
        var scriptElement = document.createElement('script');

    2. set the type of the newly created element
        scriptElement.type = "text/javascript";

    3. set the src attribute of the element
             scriptElement.src = "script/TestScript.js";

    4. get the head element and inject the script element inside it
         var headElement = document.getElementsByTagName('head')[0];
         headElement.appendChild(scriptElement);

Putting it together :

<head runat="server">  
 <script type="text/javascript">
     var scriptElement = document.createElement('script');
     scriptElement.type = "text/javascript";
     scriptElement.src = "script/TestScript.js";
     document.getElementsByTagName('head')[0].appendChild(scriptElement);
 </script>
</head>

Conclusion

Please create these files in your local or load existing one and open your firebug - open the head tag you can see the main.js only added now click on the first button you can see the js1.js and style.css added to your head tag, it opens the div and div has the CSS class property and by clicking on the box1 button it is alerting alert("box1 function"); Repeat the process when you click the box2 button. Thanks.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here