开发者

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

    var head =document.getElementsByTagName("head")[0];  
            newScript = document.createElement('script');
     开发者_C百科   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?


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.


Looks like this is an issue with innerHTML being used in a readonly element. This happens too when you try to set innerHTML in tbody. According to msdn documentation:

(...) Doing this can also be a little tricky because you cannot use innerHTML to inject into the HEAD or STYLE element directly. (Both of these tags are READ ONLY.) The best way to dynamically add styles to a page is to wait for the document to load, and then create the rule in a new style sheet.

Why is it a readonly attribute? Here is an explanation.

So, you need to use a DOM approach to do this dynamic loading. Check this link to load external javascript resources and this one to inline scripts which is your case.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜