Friday, February 09, 2007

SCRIPT and innerHTML: a losing combination

One day you may be tempted to skip all the cumbersome creation of SCRIPT elements via DOM methods and just cram stuff into the page with innerHTML. Woe unto you. This does not work:

var script = '<script type="text/javascript">alert("boo");</script>';
document.body.innerHTML = script;

In fact, this will produce an unterminated string error in IE6 and Firefox, because you still need to split up that closing </script> like in ye olde days:

var script = '<script type="text/javascript">alert("boo");</scr' + 'ipt>';
document.body.innerHTML = script;

Hooray, no error!

Except it still won't execute the script.