Can scripts be inserted with innerHTML?
I tried to load some scripts into a page using innerHTML with a div. It appears that the script loads into the dom, but it is never executed (at least in ff and chrome). Is there a way to have scripts execute when inserting them with innerHTML?
sample code
<!DOCTYPE html>
<html><head>
<title>test</title>
</head>
<body onload="document.getElementById('loader').innerHTML = '<script>alert(\'hi\')<\/script>'">
Shouldn't an alert saying hi appear?
<div id="loader"></div>
</body></html>
Solution:
You have to use eval() to execute any script code that you’ve inserted as DOM text.
MooTools will do this for you automatically, and I’m sure jQuery would as well. This saves a lot of hassle of parsing out <script>
tags and escaping your content, as well as a bunch of other “gotchas”.
Generally if you’re going to eval()
it yourself, you want to create/send the script code without any HTML markup such as <script>
, as these will not eval()
properly.