How to load js file dynamically using js


I’m trying to load a js file dynamically when a page load. Below i given the code what i’m using.

var script = document.createElement(‘script’);
script.type = ‘text/javascript’;
script.src = ‘…/…/Scripts/ChatMessage.js’;

HEre the problem is the script file is not loading. After the alert message (which i commented on above code )it is working fine. I tried to given wait time more than 10 second even though its not loading.

But after giving the alert box, its working.

Can anybody say the reason why its happening like this.

S. Ramkumar

Where in the page do you have the script?

In order for that script to work the head element must have already fully loaded and so that code will work if placed anywhere in the body of the page but will fail if you try to run it directly in the head.

You do then need to wait for long enough after requesting to load the script for it to actually load before you can run anything in it so the best place to put whatever you want to run using the script that you are loading is inside of that file. If you can’t do that then you need to set up a loop to test for something created at the end of that file existing before you try to run anything.

Is the script inside the HEAD of your page? Could you be trying to add the script to an element which hasn’t yet been closed? If so, it probably can’t be referenced via the DOM. I suspect the HEAD is still loading while the ALERT is sat on the screen, so it gives it the delay it needs to complete.

Here’s some JS I used to add jQuery to a page if it didn’t exist before running another script which relied on it being loaded. It keeps checking (after a slight delay) for jQuery to be defined before continuing.

// Add jQuery
    if (typeof jQuery == 'undefined') {  
      var FB_JQ = document.createElement('script');
        FB_JQ.src = '/core/js/jquery.js';
        FB_JQ.type = 'text/javascript';

// Check if jQuery's loaded
    function FB_wait() {
      if (typeof jQuery == 'undefined') {  
      // If jQuery is loaded
      else {
        // Make sure body is loaded
        jQuery('document').ready(function () {
          var t=setTimeout("FB_addBadge()",3000);

Hope it helps!

Thanks to you all for the response.

my problem solved. I given time delay and i moved the code below after adding script dynamically to separate function and i called that method using "setTimeOut(fnName(),100);

Its works.

Thanks again to you all.

S. Ramkumar