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.

var myScript = document.createElement("script");
     myScript.innerHTML += 'alert("Hello from");';

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.

// instead of 
ScriptDiv.innerHTML = sHTML + sScript;
// we can use
var container = document.getElementById('ScriptDiv');
     container.innerHTML = sHTML + sScript;

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.