WISDOMBAY

in4mation ... organized

How to Dynamically load JavaScript Source files to a webpage

Article Written by Pramod S Nair for www.wisdombay.com

This article explains the method of dynamically including external javascript source files into a web page based on user interaction. The article explains the method of dynamically injecting javascript source into an already loaded webpage.

The Logic

The logic to do this is very simple, create a script element and set the 'type', 'language' and 'src' attributes of the newly created element using obj.setAttribute method. Then all we have to do is to slip in this newly created element in to the Head node of the page and the code contained inside the javascript source file will get executed. This can be done by using the below given code snippet.


  //Create a 'script' element	
  var scrptE = document.createElement("script");

  // Set it's 'type' attribute	
  scrptE.setAttribute("type", "text/javascript");

  // Set it's 'language' attribute
  scrptE.setAttribute("language", "JavaScript");

  // Set it's 'src' attribute
  scrptE.setAttribute("src", "myjsfile.js");

  // Now add this new element to the head tag
  document.getElementsByTagName("head")[0].appendChild(scrptE);
  

To expand on the idea i am giving you a sample code. You can view it HERE. All the files included in this sample can be downloaded from HERE (2KB Zip file)

What does the sample do

The sample page presents the user with two buttons. Clicking on the first button will fetch an external javascript file named 'showtime.js' and executes it's contents thereby showing a message with the current time. Clicking on the second button will fetch an external javascript file named 'showquote.js' and executes it's contents thereby showing a message with a random quote. The below given function controls the dynamic inclusion of the two script files based on the button which is clicked.


function loadjs(i)
{
  // If button 1 is pressed then i will be 1 else i will be 2

  //Create a 'script' element	
  var scrptE = document.createElement("script");

  //Set 'type' and 'language' attribs 
  scrptE.setAttribute("type", "text/javascript");
  scrptE.setAttribute("language", "JavaScript");

  // Now set it's 'src' attribute based on the value of i
  if (i==1)
  {
  scrptE.setAttribute("src", "showtime.js");
  }
  else
  {
  scrptE.setAttribute("src", "showquote.js");
  }

  // create an object of the head element of current page
  var hdEl = document.getElementsByTagName("head")[0];

  //check for previously appended child 
  //(it ensures that each time the button is pressed it
  // removes the previously loaded script element)
  if (hdEl.childNodes.length > 1) {
   hdEl.removeChild(hdEl.lastChild);
  }

  // Now add this new element to the head tag
  hdEl.appendChild(scrptE);

}
  

That is all that is required to dynamically inlude a javascript source file to a webpage based on user inputs.


Google