Whereas the XMLHttpRequest technique allows you to download individual code
external domains and the script will be included in the browser cache.
Setting a Script's
A script element's
src property can be used to load a new script at any time.
Previously-loaded scripts remain in memory, even after the
src property has changed.
Here's how to do it:
Dynamically Creating the <SCRIPT> Element
This technique goes further by dynamically creating the element from scratch.
DOM methods are used to reference the
HEAD portion of the document, create a
new script element, set its
src properties, and append it to the
Writing a Script Element Using
document.write()function. Although easy to use, it does have a limitation in that it must be called during the loading of the page; otherwise, it will clobber the existing document! You must also pay attention to include the "/" escape character in the closing
Here's a real life example of the above technique:
loadMootools() function uses
document.write() to add the script to the page.
initScripts() function includes all the required functionality to delegate
Prototype methods to equivalent MooTools ones or to those from own library:
Script Loading Tools
There are already plenty of excellent libraries out there that utilize dynamic
script loading. Some are limited to their own modules, while others can be used
to import a variety of resources.
The Dojo JS Library
leads to the storing of scripts in online repositories so that developers can
access a multitude of code snippets for every usage. Their method of including
modules is called
JSAN.use(). Here's an example of a script that performs a
test using a JSAN library:
The Persevere Framework
Persevere is an open source set of tools for persistence and distributed computing
using the JSON interfaces of HTTP REST, JSON-RPC, JSONPath, and REST Channels.
Original: March 18, 2009