Firefox 4 bug adding inline script tag - last tag doesn't fire

I came across a nasty bug in Firefox 4 today, which will break a lot of AJAX.

All script tags fire, except for the last one, eg:


function test(num) {
    var temp = document.createElement('div');
    var src  = '<script type="text/javascript">' +
                       'alert("Hi");'  + 
                    '<' + '/script>';
    if (num === 2) {
        src = src + '<script></' +'script>';
    }
    temp.innerHTML = src;
    body.appendChild(temp);
}


Calling test(1) will do nothing, while test(2) will produce an alert popup.

Reported as bug: https://bugzilla.mozilla.org/show_bug.cgi?id=645115

1 Comment

If you look at your bug, they are actually wondering why the script content executes at all. The reason it is not supposed to run is because Firefox 4 uses a HTML5 engine by default, and according to the HTML5 spec:
"Note: script elements inserted using innerHTML do not execute when they are inserted."
You can see this as the note at the end of section 2.5.2 Dynamic markup insertion in HTML.

If you are looking to add script to the document dynamically there are several methods:
1) Adding an external script:
var s = document.createElement('script');
s.async = "async";
s.src = url;
document.head.appendChild(s);
2) Executing data you have in a string (like your examples) using a global eval:
var globalEval = eval;
globalEval(scriptData);
3) Executing data you have in a string (like your examples) through a script element:
var s = document.createElement('script');
s.textContent = scriptData;
document.head.appendChild(s);

You may not even want to hand-roll this yourself either. Looking at part of the jQuery source (https://github.com/jquery/jquery/blob/master/src/ajax/script.js) is always a god starting point.

Leave a comment

About Clinton Gormley

user-pic The doctor will see you now...