Skip to content

Instantly share code, notes, and snippets.

@ExperimentGarden
Created June 14, 2010 19:04
Show Gist options
  • Save ExperimentGarden/438118 to your computer and use it in GitHub Desktop.
Save ExperimentGarden/438118 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Ajax JavaScript Includer</title>
<script type='text/javascript' src='jquery-1.3.2.min.js'></script>
<script type='text/javascript'>
//We have to declare a global object that we will use as a namespace for storing
//the eval loaded functions and variables, otherwise they will only exist within
//the scope of the ajax response function, which is be useless.
var fooNamespace = new Object();
//The list of loaded resources.
var loaded = new Array();
//The list of resources that have yet to be loaded.
var loading = new Array();
//Whether or not we are currently loading a resource via AJAX.
var currentlyLoading = false;
function loadAjax(resourceUrl)
{
$.ajax({type: "GET",
url: resourceUrl,
success: function(responseText)
{
//Set up the variables and functions loaded.
eval(responseText);
//This item is loaded, remove from queue.
loading = loading.slice(1,loading.length);
//Add it to the already loaded queue.
loaded[loaded.length] = resourceUrl;
//Now check the load queue for another item to load.
if(loading.length>0)
{
//Load the first item in the queue via AJAX.
loadAjax(loading[0]);
}
else
{
//We are done loading logic via AJAX.
currentlyLoading = false;
}
}
});
}
function include(resourceUrl)
{
//Check to see if this resource has already been loaded.
for(var i=0; i<loaded.length; i++)
{
if(loaded[i]==resourceURL)
{
return;
}
}
//Store the in the loading queue.
loading[loading.length] = resourceUrl;
//Now check to see if we are already running an ajax request.
if(currentlyLoading == true)
{
return; //The current loading process will work its way through the queue.
}
loadAjax(resourceUrl);
currentlyLoading = true;
}
//This makes it easy to execute a function after all items to be included are
//loaded.
function waitForInclude(afterSafeFunction)
{
if(loading.length==0)
{
afterSafeFunction();
}
else
{
//Wait 100ms and then try again.
setTimeout("waitForInclude("+afterSafeFunction+")",100)
}
}
include("4_setFoo.js");
include("4_outputFoo.js");
waitForInclude(function()
{
fooNamespace.setFoo("Foo was set using a function loaded via AJAX, and output using another function loaded via AJAX.");
fooNamespace.outputFoo();
})
</script>
</head>
<body>
This is a basic test of loading JavaScript code via AJAX and then running it.
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment