Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
like image 515
John Bachir Avatar asked Feb 11 '11 20:02

John Bachir


People also ask

How do I show the script tag in HTML?

To add a script, use the <script> tag. The HTML <script> tag is used for declaring a script (such as JavaScript) within your HTML document. Defines the character encoding that the script uses. Declares that the script will not generate any content.

Are script tags executed in order?

Script tags are executed in the order they appear It also means scripts which appear later on the page can depend on things scripts which appear earlier have done. Elements on the page won't render until all the script tags preceding them have loaded and executed.


1 Answers

Try following code:: Its working

  var script = document.createElement( 'script' );
  script.type = 'text/javascript'; 
  script.src =MY_URL; 
  $("#YOUR_ELEMNT_ID").append( script );
like image 125
Manish Trivedi Avatar answered Oct 10 '22 20:10

Manish Trivedi