0

I am trying to add a script tag dynamically through Javascript in my HTML page. Just after the code I am trying to call a few functions of the newly added script. However, I am getting JS errors because by that time the script has not loaded yet. I have gone through multiple posts but none of them explains how to execute your script added explicitly.

dda
  • 6,030
  • 2
  • 25
  • 34
  • 1
    Please edit your question to include the code you have so far and the exact error message you're getting. – Jordan Running Jan 29 '17 at 05:01
  • 1
    the few functions you are trying to be called should be in a seperate JS & It should be loaded after your script is loaded ..! Code here would be helpful along with exact error message. – Parth Ghiya Jan 29 '17 at 05:03

2 Answers2

0

You need to listen for the onload event of your newly added script, or onreadystatechange for IE < 11.

var script = document.createElement('script');

script.onload = function() {
  // it's ready, so call your functions here
}

// now insert your new script into the document

For IE < 11:

script.onreadystatechange = function() {
  if (script.readyState === 'loaded' || script.readyState === 'complete') {
    // it's ready, so call your functions here
  }
}
shadymoses
  • 3,273
  • 1
  • 19
  • 21
0

This will allow you to execute scripts when and only when the whole page has loaded. There are other ways to do this but I think this one is simple and effective:

<script>
     function downloadJSAtOnload() {
         var element = document.createElement("script");
         element.src = './js/ding.js';
         document.body.appendChild(element);
         var element1 = document.createElement("script");
         element1.src = './js/dong.js';
         document.body.appendChild(element1);
     }
     if (window.addEventListener)
         window.addEventListener("load", downloadJSAtOnload, false);
     else if (window.attachEvent)
         window.attachEvent("onload", downloadJSAtOnload);
     else window.onload = downloadJSAtOnload;
</script>

Place it on your page at the end of the body tag. Anything imported by this block of code will execute dead last, ensuring all scripts called in the head will be there.

I use this pattern all over the place because it is semantic. My 'library' type scripts are loaded in my head, and then my custom code waits for the whole dom to render before it executes.

Geoff_Clapp
  • 161
  • 1
  • 5