Created
January 31, 2011 23:30
-
-
Save heisters/805062 to your computer and use it in GitHub Desktop.
A robust remote JS dependency manager
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
var require = (function(){ | |
var requires = {}; | |
return function(filename, callback){ | |
if(typeof(requires[filename]) === "undefined"){ | |
requires[filename] = { | |
callbacks: [], | |
state: "initializing", | |
}; | |
} | |
var state = requires[filename].state; | |
if(callback){ | |
if(state === "done"){ | |
callback(); | |
return; | |
} else { | |
if(callback) requires[filename].callbacks.push(callback); | |
} | |
} | |
if(state === "initializing"){ | |
requires[filename].state = "fetching"; | |
$.getScript(filename, function(){ | |
requires[filename].state = "done"; | |
$.each(requires[filename].callbacks, function(){ | |
this(); | |
}); | |
}); | |
} | |
}; | |
})(), | |
// require("http://example.com/foo.js"); | |
// require("http://example.com/foo.js", function(){alert("loaded!")}); | |
// // User will see "loaded!" once. Allows you to pre-load the JS a rest assured that the callback will be called exactly once |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment