Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you execute a dynamically loaded JavaScript block?

I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:

<div>   <!-- some html -->   <script type="text/javascript">     /** some javascript */   </script> </div> 

I'm inserting the whole thing into the DOM, but the JavaScript isn't being run. Is there a way to run it?

Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed. I can't call eval on the response because the JavaScript is within a larger block of HTML. I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky. Anyone know a better way?

like image 230
kristina Avatar asked Sep 16 '08 19:09

kristina


People also ask

How do you load a JavaScript script?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.

How do you execute JavaScript?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.


2 Answers

Script added by setting the innerHTML property of an element doesn't get executed. Try creating a new div, setting its innerHTML, then adding this new div to the DOM. For example:

 <html> <head> <script type='text/javascript'> function addScript() {     var str = "<script>alert('i am here');<\/script>";     var newdiv = document.createElement('div');     newdiv.innerHTML = str;     document.getElementById('target').appendChild(newdiv); } </script> </head> <body> <input type="button" value="add script" onclick="addScript()"/> <div>hello world</div> <div id="target"></div> </body> </html> 
like image 155
Ed. Avatar answered Sep 22 '22 08:09

Ed.


You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.

div.innerHTML = response; var scripts = div.getElementsByTagName('script'); for (var ix = 0; ix < scripts.length; ix++) {     eval(scripts[ix].text); } 
like image 28
Scott Nichols Avatar answered Sep 24 '22 08:09

Scott Nichols