Last active
August 29, 2015 14:09
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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