To eval or not to eval?

written by Tobie on February 23rd, 2007 @ 05:15 PM

Thanks to Yehuda Katz having to deal with cross-browser discrepancies in some legacy code, we bumped into an interesting issue.

Consider the following code snippet:

var script = document.createElement('script');
var text = document.createTextNode("alert('hello world!')");
script.type = 'text/javascript';
script.appendChild(text);
document.body.appendChild(script);

Safari, Firefox and Opera all trigger the alert. IE6 and IE7 both don't and throw a runtime error instead (Unexpected call to method or property access). Try it out!

Now it's very unclear to me what the correct behavior should be (i.e. if the JavaScript enclosed in the script tag should be evaluated or not), but I have the slight impression that Internet Explorer is in the wrong here again.

Your thoughts ?

Note that the below, although non-standard compliant, triggers the alert in all browsers but Safari (it works in WebKit though).

var script = document.createElement('script');
script.type = 'text/javascript';
script.text = "alert('hello world!')";
document.body.appendChild(script);

Try it out too!

Comments

  • Kevinin
    Kevinin says:

    I am probably wrong, but it might have something to do with the “defer“-property of IE.

    Thu, March 22 at 19:15 PM

Comments are closed