me, myself & andrei

29 Sep 2006
AJAX, onDemand JavaScript or Dynamic Script Tags

Now, with Web 2.0 being closer and closer (actually it is already alive!) you don’t just make asynchronious requests in order to get HTML or JSON… but ALSO JavaScript.

To be more exact… you make requests to get HTML with SCRIPT tags.

But the “beauty” is that the SCRIPT blocks don’t get loaded/evaluated/ran. This if you AJAX for a response like

some other HTML

and put this in the innerHTML of a DIV element, then you will not get your my.js loaded. The same happens if you put actual scripting code inside the SCRIPT block.

The first thing you think of (or at least I thought of) is to assign the response to a DIV element, then parse it to find any SCRIPT tags.

For each SCRIPT element you do this

for (var i in scriptElements) {
var scriptElement = scriptElements[i];
var newScript = document.createElement('SCRIPT');
newScript.setAttribute('src', scriptElement.getAttribute('src'));
newScript.setAttribute('type', scriptElement.getAttribute('type'));
newScript.setAttribute('id', scriptElement.getAttribute('id'));
newScript.data = scriptElement.data;
if (_isMSIE_)
{
newScript.onreadystatechange = function ()
{
if (newScript.readyState == 'loaded')
{
_do your thing_
newScript.onreadystatechange = null;
}
}
}
else
{
newScript.onload = function() {_do the same thing_}
}
scriptElement.parentNode.removeChild(scriptElement);
var head = document.getElementsByTagName("head")[0];
head.appendChild(newScript);
}

Be sure to retain the IDs of the SCRIPT elements, so that you can eliminate them later, if you need to do this.

This should fix it. BUT… there's also Internet Explorer! It always is.

When you try to put the example AJAX response into an element's innerHTML, the SCRIPT tags dissappear!!! Why?! I do not know. Maybe it is because it will not load the SCRIPT anyway, so it erases it.

The solution I came up with is: why should you need to use the SCRIPT tag when responding to the AJAX request? I respond with a normal "innocent" DIV tag like this:

Then, when you search for "SCRIPT" elements, you can search for elements with type == "text/javascript", etc.

Et voila! Enjoy!


Andrei