Inserting SCRIPT tags at runtime

If you ever tried to create a script tag and add it to the DOM, you probably discover that it works fine in Mozilla browser, but not as well in IE.

For the SCRIPT tag IE doesn’t allow modifying the innerHTML value of your new HTMLElement. In one of the Microsoft page they explain how to insert a script after the pages was constructed (innerHTML Property).

This is what you will see in Microsoft’s Example:

Its’ a kind of tricky, but this approach does not work in Mozilla browsers. The DEFER value is need by IE and it doesn’t help Mozilla browsers. To make it compatible we have to avoid accessing elements directly. Getting a reference by the element ID will be a more compliant approach.

In a real world you may not want to insert a button to trigger the new script and you just some new code to be executed, so we can remove the ‘Click’ button and add our own code.

Custom Example:

The new SCRIPT tag can be inserted but the code does not execute in IE. Removing the button makes IE ignore the script. It seems like a visual element must be added for this to work. Instead of removing the button we can replace with an invisible element.

IE and Mozilla compatible:

This is a good example if we know ahead of time what the code that we want to execute. If we want to add dynamic values to our code we have to use a more generic approach:

Enhanced Version:

As you can see this approach will let us include a script that is in a different URL or create a string with any dynamic value.

If you ever wonder why the function returns the new script tag id, well, that why I wrote this post. I needed to dynamically add an script tag to listen to events in a windows media player object. To do that, I had to add a script tag that contains attributes such ‘FOR’ which points to the windows media player instance (object id) and ‘EVENT’ which refer to the player event you want to listen to. Well the script above works fine but the ‘EVENT’ attribute is ignored. A way to work around is adding the ‘EVENT’ attribute after the script tag was appended to the DOM. This is why convenient to have the script tag id.

Click HERE to test this functionality.

AOL Top 11 Widget

It is difficult to keep the house clean. I was going over the posts of my old blog, and I discovered that one of toys that I created for AOL in 2006 is still alive. I am sure folks from AOL would not mind that gives free promotion to the Top 11 show , while I use the opportunity to show a cool little thing that I built when I work there.

The embed code below can be acquired from the widget itself.