jQuery.Deferred objects provide a very elegant way to do this (I know you are not using jQuery 1.5: I just give you a reason to update ;-) :
Assuming we have two scenarios interacting as shown below:
// defines utilities var util = util || { loaded: $.Deferred() }; (function(){ $.extend(util, { msg: "Hello!" }); util.loaded.resolve(); })();
... and:
// uses them var util = util || { loaded: $.Deferred() }; util.loaded.then(function(){ alert(util.msg); });
... a warning will always be triggered after the first script had the ability to determine its utilities regardless of the order in which they are loaded. This has advantages over setTimeout and event approaches, has several dependencies (using $.when ), doesn’t use polling, and you don’t have to worry about handling the load order explicitly.
The only thing that is gross is that all modules should include:
var util = util || { loaded: $.Deferred() };
... and $.extend() to make sure they use the same pending.
Aaron maenpaa
source share