I tried to load some scripts into a page using innerHTML
on a <div>
. It appears that the script loads into the DOM, but it is never executed (at least in Firefox and Chrome). Is there a way to have scripts execute when inserting them with innerHTML
?
Sample code:
<!DOCTYPE html>
<html>
<body onload="document.getElementById('loader').innerHTML = '<script>alert(\'hi\')<\/script>'">
Shouldn't an alert saying 'hi' appear?
<div id="loader"></div>
</body>
</html>
Execute (Java Script) tag from innerHTML
Replace your script element with div having a class attribute class="javascript" and close it with
</div>
Don't change the content that you want to execute (previously it was in script tag and now it is in div tag)
Add a style in your page...
<style type="text/css"> .javascript { display: none; } </style>
Now run eval using jquery(Jquery js should be already included)
You can explore more here, at my blog.
My solution for this problem is to set a Mutation Observer to detect
<script></script>
nodes and then replace it with a new<script></script>
node with the same src. For example:Use
$(parent).html(code)
instead ofparent.innerHTML = code
.The following also fixes scripts that use
document.write
and scripts loaded viasrc
attribute. Unfortunately even this doesn't work with Google AdSense scripts.Source
Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too
So use this instead of script tags:
<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />
Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.
Enjoy his solution:
http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element
Important notes:
You could do it like this: