Javascript – How to insert javascript using innerHTML (ie6 is giving me a unknown runtime error)

internet-explorer-6javascript

    var head =document.getElementsByTagName("head")[0];  
            newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.innerHTML = '$(window).load(function(){ someFooo(); }); ';
        head.appendChild(newScript);

This is causing an Unknown Runtime Error in IE6. Any other way around this?

Best Answer

Try the text property instead:

newScript.text = '$(window).load(function(){ someFooo(); });';

This works in non-IE browsers as well. I've used this in FF2, FF3, FF3.5, Safari 4 (win), Opera 9+, Chrome 2, Chrome 3, and they all work.

According to the spec (I have to say this otherwise I feel misleading), you're supposed to use appendChild:

var script = '$(window).load(function(){ someFooo(); });';
newScript.appendChild(document.createTextNode(script));

But that fails in IE (<script> elements are not allowed to have children or some other inane IE thing). So just go with the former.