I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.
you can load script dynamically by adding <script src="...">
tag to DOM tree.
function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
And to use (I used swfObject as an example):
var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
callbackMethod();
You might want to take a look at jsloader: http://www.jsloader.com/
Gaia Ajax does this (I know since I implemented it - I'm the original founder) and they're GPL. So unless you're afraid they'll sue you (they're FUDding me with lawsuits now) you might want to check out how they do it. Basic technology is to inject a script tag using DOM when script is needed. Though you must take care NOT to reference stuff in this file before it is finished loading (which happens asynchronously)
The solution to that problem (one solution) is to add up a variable at the bottom of the file and use recursive setTimeout calls to check if the variable is defined and defer execution of the code depending on the file being finished loading until that "bottom of JS file" variable is defined...
We actually also tracked which files where included by appending the hashed value of the filenames into a hidden field on the page. This means we never ended up including the same file more then once...
Pretty nifty in fact...
The Google AJAX APIs provide dynamic loading for Google's JavaScript APIs. There is an example of loading the Maps JS on-demand in the documentation:
function mapsLoaded() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
}
function loadMaps() {
google.load("maps", "2", {"callback" : mapsLoaded});
}