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?
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.
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.
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>
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With