Aaron Yodaiken
Aaron Yodaiken

Reputation: 19561

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.

Upvotes: 2

Views: 489

Answers (3)

kennebec
kennebec

Reputation: 104840

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);

Upvotes: 6

xavierm02
xavierm02

Reputation: 8787

document.getElementsByTagName('head')[0]*;*.appendChild(scr);

Why did you put a semicolon here?

Upvotes: 0

jfriend00
jfriend00

Reputation: 708036

If you already have the code in a string, why make a script tag out of it? Can't you just call eval(script) on it. Won't that do the same thing?

Upvotes: 1

Related Questions