I added this post for my future reference. Today I spend 1 hr for solving this small issue.

dynamically I want to add some javascript piece to script  tag in runtime:

Usually we will do like this:

var head= document.getElementsByTagName(‘head’)[0];

var scriptTag= document.createElement(‘script’);

scriptTag.type= ‘text/javascript’;

scriptTag.innerText = result;

document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);

But in IE

you have to use  "text" in place of "innerText"

 var head= document.getElementsByTagName(‘head’)[0];

var scriptTag= document.createElement(‘script’);

scriptTag.type= ‘text/javascript’;

scriptTag.text = result;

document.getElementsByTagName(‘head’)[0].appendChild(scriptTag);

Here result is my piece of javascript code.

 

Courtesy: http://poeticcode.wordpress.com/2007/10/03/innerhtml-and-script-tags/

RIn the wonderfully buggy world of IE, if you dynamically add a script tag to the DOM, you cannot do:

//works in modern DOM aware browsers
var scriptTag = document.createElement(’script’);
scriptTag.appendChild( document.createTextNode( ‘your js code here’ ) );

//in IE, you can’t do the above (it will just ignore the code), you need to do:
var scriptTag = document.createElement(’script’);
scriptTag.text = ‘your js code here’;

Yet another ugly IE hack.

PS in case you haven’t encountered it yet, you’ll find a similar issue when trying to create a style tag on the fly

Advertisements

About ambatisreedhar

Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s