Search code examples
javascriptinternet-explorerinternet-explorer-7internet-explorer-6

ie6/7 script tag population giving "unexpected call to method or property access"


I use AJAX to get the content of a script, and then use the following code:

    var scr = document.createElement('script');
    scr.appendChild(document.createTextNode(script)); // ***
    document.getElementsByTagName('head')[0].appendChild(scr);

Where script is astring populated from AJAX. This works fine in IE9, Chrome and Firefox. However, in IE6 and 7 I get an error:

Unexpected call to method or property access

IE gives the number of the the line indicated with the // ***.

Although there are multiple other questions about this, none of the appear to address this precise issue.


Solution

  • Older IE's do not accept child nodes in script elements ( or in style and option elements, but that's another two questions).

    You can set the script element's text property instead. (scripttext is a string of, well, script text.)

    var scr = document.createElement('script');
    if(window.addEventListener)scr.appendChild(document.createTextNode(script))
    else scr.text=scripttext;
    document.getElementsByTagName('head')[0].appendChild(scr);