Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create script tag in IE8

I was testing our site, in IE8 and got the dreaded Unexpected call to method or property access. error.

After lots of debugging (IE8's devtools suck), I found the offending line.

$('<script>').html(JSData).appendTo('head')

The problem is $('<script>').html(JSData). I tried running just that in the console, and I still got the error.

Why can't IE8 set the .html on a newly created script tag?

P.S. This fails too:

$(document.createElement('script')).html(JSData)

UPDATE: I tried to create the script tag without jQuery:

var scriptTag = document.createElement('script');
scriptTag.type = 'text/javascript';
scriptTag.innerHTML = JSData;

On the scriptTag.innerHTML = JSData; line, IE8 gives Unknown runtime error. Thanks IE8.

like image 756
Rocket Hazmat Avatar asked Aug 30 '12 16:08

Rocket Hazmat


1 Answers

Your javascript only method needs to add the script element to the document.

IE<9 does not recognize innerHTML or childNodes on script tags, but all browsers support the text property.

var scriptTag = document.createElement('script');
scriptTag.text= JSData;
document.body.appendChild(scriptTag);
like image 165
kennebec Avatar answered Sep 19 '22 17:09

kennebec