Click here to Skip to main content
15,883,814 members
Articles / Web Development / CSS

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
10 May 2013CPOL4 min read 53.4K   12   6
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:

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

Adding a CSS file dynamically:

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

XML
<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>">
<html>
<head>
<title>Demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script src="javascripts/main.js"></script>
</head>
<body>
 <input type="button" name="check1" id="check1" 
     value="box1" onClick="showbox('box1')">
 <input type="button" name="check2" 
   id="check2" value="box2"  onClick="showbox('box2')">
 
 <div style="display:none;" id="box1">
  <input type="button" onClick="function1()" 
    value="Box1 function1() call in (js1.js) file">
 </div>
 <div style="display:none;" id="box2">
  <input type="button" onClick="function2()" 
    value="Box2 function2() call in (js2.js) file">
 </div>
</body>
</html></div>

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:

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

javascript"
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:

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

JavaScript
// 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 -

JavaScript
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 :

JavaScript
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
SuggestionMaybe you could also... Pin
Dennis E White9-Jan-14 4:46
professionalDennis E White9-Jan-14 4:46 
GeneralMy vote of 5 Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)13-May-13 1:06
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)13-May-13 1:06 
GeneralRe: My vote of 5 Pin
Sisir Patro13-May-13 1:43
professionalSisir Patro13-May-13 1:43 
Thanks Tadit, Smile | :)
Thanks & Regards
Sisir

GeneralRe: My vote of 5 Pin
Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)13-May-13 2:49
protectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)13-May-13 2:49 
GeneralRe: My vote of 5 Pin
Sisir Patro13-May-13 23:28
professionalSisir Patro13-May-13 23:28 
GeneralMy vote of 5 Pin
Volynsky Alex10-May-13 5:59
professionalVolynsky Alex10-May-13 5:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.