John Bachir
John Bachir

Reputation: 22711

How can I tell a dynamically inserted <script> tag to… run

I'm dynamically inserting a <script> tag with a src attribute and no content. But the browser does not pull down that src and run the script after the insertion -- the tag just sits there in the DOM.

Is it possible for me to tell the browser to "run" the script tag?

Because of the other code I'm working with, it's easier for me to keep the code fetched via the src attribute than to fetch it myself and insert it into the body of the tag -- but if that's necessary, I can do that too (and welcome any advice on that).

update with requested info

  1. The script tag is inserted based on user interaction an arbitrary number of times after the page has loaded
  2. I'm inserted the tag like this (jquery's html function strips out script tags): document.getElementById("my-div").innerHTML = "the script tag, which stack overflow wants to strip";

Upvotes: 10

Views: 9838

Answers (3)

gion_13
gion_13

Reputation: 41533

it should run right after the browser inserts the script into the dom, but you can try to wrap your script into a function and call that function after the script loads :

var script = document.createElement('script');
script.setAttribute('type','text/javascript'); 
script.setAttribute('src',script_url); 
script.onreadystatechange= function () {
    if (this.readyState == 'complete') 
        initScript();//the whole script is wrapped in this function
}
script.onload= initScript;

Hope this helps!

Upvotes: 2

Manish Trivedi
Manish Trivedi

Reputation: 3559

Try following code:: Its working

  var script = document.createElement( 'script' );
  script.type = 'text/javascript'; 
  script.src =MY_URL; 
  $("#YOUR_ELEMNT_ID").append( script );

Upvotes: 4

Kavi Siegel
Kavi Siegel

Reputation: 2994

You could have a setTimeout in the main script to check if the new script is there.. and if it is, then run it. Do you know if it downloads the file or if it just does nothing? Check with Chrome's Network monitor.

I think there's a dynamic way to load Javascript without the src= tag, as well, but I haven't personally done it.

Why not have all the javascript pre-loaded and just put through some inline JS to execute it?

Upvotes: 0

Related Questions