I came across this technique when I was trying to get around the cross-domain restrictions applied by modern browsers to the XMLHttpRequest object. Basically you can't do it.

This got me thinking, how does Google Maps do it? I have Google Map code in pages hosted on my domain. Somehow it's going to the Google server, from the browser, to get images. It can't be using XMLHttpRequest to do it, so how does it work?

Its seems ridiculously simple. You can reference scripts from another domain. You can use javascript to manipulate the DOM and web servers can deliver dynamic content based on a request.

So all we have to do to dynamically request a dynamic script is run some javascript that will insert a script tag with the source attribute pointing to the desired URL in the document head tag. The browser will then request the script from that URL. The server can return a script based on the request parameters provided. When the browser receives the script it will add it to the DOM.

My example here doesn't actually get the scripts off an external server or dynamically generate the script. The example has buttons that insert a script element into the head element when clicked. The script elements source attribute depends on which button is clicked, but both local script files display an alert message when loaded.

Download Demo (> 1k)

To see this example running, just open the folder as a Website in Visual Studios and run it. I'll add a link to a live demo soon.

While this works really well, I will go into a light-weight Javascript framework I wrote that wraps round this concept and provides response, timeout and some error handling events as you would expect in most XMLHttpRequest wrappers.