Skip to content

Instantly share code, notes, and snippets.

@samuelcole
Created March 9, 2010 18:48
Show Gist options
  • Select an option

  • Save samuelcole/326933 to your computer and use it in GitHub Desktop.

Select an option

Save samuelcole/326933 to your computer and use it in GitHub Desktop.
$.requires function for loading external javascript requirements
window.requires_urls = {};
(function($){
$.requires = function(url, callback) {
// look for the url in our cached url results
for(called_url in window.requires_urls) {
var cached = window.requires_urls[called_url].cached;
// if a url matches and it has cached results
if(url_equals(url, called_url) && cached.data) {
// run the callback, if any
if(callback) callback(cached.data, cached.textStatus);
// return the xmlHttpRequest, and we're done
return cached.data.xmlRequest;
}
}
// this will be the xmlHttpRequest from the first time we called this url
var xmlRequest;
// if we haven't heard of this url before
if(!window.requires_urls[url])
{
// build it's data structure
window.requires_urls[url] = {
callbacks : [],
cached : {}
};
// push this callback into the queue of callbacks
window.requires_urls[url].callbacks.push(callback);
// do the ajax request, storing the xmlHttpRequest
xmlRequest = $.ajax({
url: url,
type: 'get',
cache: true,
dataType: 'script',
global: false,
success: function(data, textStatus) {
// after the request finishes do:
// for each callback in the queue
var callbacks = window.requires_urls[url].callbacks;
for (var i in callbacks) {
var this_function = callbacks[i];
// run it if it a function
if(typeof this_function == 'function') this_function(data, textStatus);
}
// empty the queue
window.requires_urls[url].callbacks = [];
// cache the results of the ajax
window.requires_urls[url].cached = {data: data, textStatus: textStatus, xmlRequest: xmlRequest};
}});
// store the xmlHttpRequest
window.requires_urls[url].cached.xmlRequest = xmlRequest;
} else {
// we have heard of this url before so:
// grab the xmlHttpRequest from the first call
xmlRequest = window.requires_urls[url].cached.xmlRequest;
// and push our callback into our queue
window.requires_urls[url].callbacks.push(callback);
}
// return the xmlHttpRequest
return xmlRequest;
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment