Dynamically adding JavaScript script tags at runtime

This is a report from here

First Let’s discuss about the issue of loading all the javascript files together at a stroke.

  1. 1. Javascript will not allow parallel download. So the browser will not start any other download until it loads the javascripts.
  2. 2. We use to load javascript files and methods which are unnecessary for that page. For eg: In Login page, we just need some javascripts essential for Login page, but developers will add all the javascripts in common headers.


<script language =”javascript” src=”scriptRequiredForUserProfile.js”></script>
<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>
<script language =”javascript” src=”scriptRequiredForReply.js”></script>

<script language =”javascript” src=”scriptRequiredForAddComment.js”></script>

<script language =”javascript” src=”scriptRequiredForReply.js”></script>

How to solve the above 2 issuesjQuery15204168177171158769_1337868541848?

  • Include only one script in the header.


<script src="”loadJS.js”"></script>


Now we can load the javascript dynamically using 2 ways.


Method 1:


Generate dynamic // <![CDATA[
tag using DOM


Maintain the list of javascripts that you need to download for a respective page.



var jsFilesArray = new Array();
jsFilesArray['home.html'] = new Array( ‘validation.js’, ‘home.js’ );
jsFilesArray['login.html'] = new Array( ‘validation.js’, ‘error.js’ );

Code to get File Name of the current page



function getCurrentPageName() {
    var fileName = document.location.href;
    var end = (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?");
    return fileName.substring(fileName.lastIndexOf("/")+1, end);

Code to generate dynamic tag and append to the head tag.



var head = document.getElementsByTagName("head")[0];

for (var i = 0;i<jsFilesArray[getFileName()].length;i++)
  script = document.createElement('script');
  script.id = "id_" + i;
  script.type = 'text/javascript';
  script.src = jsFilesArray[getCurrentPageName ()][i];



Click to download the code.


Method 2:


Use AJAX to load the JS file dynamically whenever required


Get the required JS file using xmlHttPRequest and execute the output by passing it into eval() method. The eval() method executes the argument.


So guys, load your Javascripts dynamically and experience improved performance of your application.


Enjoy Coding :)