Skip to content

Instantly share code, notes, and snippets.

@Tangent128
Last active August 29, 2015 14:09
Show Gist options
  • Save Tangent128/6bd3d411f79934a67f58 to your computer and use it in GitHub Desktop.
Save Tangent128/6bd3d411f79934a67f58 to your computer and use it in GitHub Desktop.
Async jQuery loader + script dependency resolver. Including this will asynchronously load jQuery, and allow other scripts to register functions to be called once jQuery is available. Importantly, you can safely use the "async" attribute when referencing this script. Dependency resolution is handled by passing the loaded functions an on-demand ge…
// each file needs to start with this to make sure the async array/object exists:
var async = async || [];
// these blocks could be in any order or different files:
async.push(function($, loaded) {
// loaded(name) returns a $.Deferred object, which modules can wait on or resolve as appropriate.
loaded("C").then(function(C) {
console.log("loaded A, needed "+C);
loaded("A").resolve("apple");
});
});
async.push(function($, loaded) {
$.when(loaded("A"), loaded("C")).then(function(A, C) {
console.log("loaded B, needed "+A+" and "+C);
loaded("B").resolve("banana");
});
});
async.push(function($, loaded) {
console.log("loaded C");
loaded("C").resolve("cherry");
});
/* Public domain, no rights reserved. */
var async = async || [];
(function() {
var JQUERY_URL = "//code.jquery.com/jquery-1.11.0.min.js";
var script = document.createElement("script");
script.src = JQUERY_URL;
script.onload = function() {
jQuery(function($) {
var loadMap = {};
function loaded(name) {
if(loadMap[name]) return loadMap[name];
loadMap[name] = $.Deferred();
return loadMap[name];
}
var queue = async;
async = {
push: function(callback) {
callback($, loaded);
}
};
$.each(queue, function(i, callback) {
callback($, loaded);
});
});
};
document.head.appendChild(script);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment