Markup-based unobtrusive comprehensive DOM-ready execution
On a recent project I took my previous approach to automating firing of onload events to a new level.
For instance if your code was architected in an object literal such as:
FOO = { common : { init : function(){ ... }, finalize : function(){ ... } }, shopping : { init : function(){ ... }, cart : function(){ ... }, category : function(){ ... } } }
A page with this body tag:
<body id="cart" class="shopping">would load these functions sequentially:
UTIL.fire is calling: FOO.common.init() UTIL.fire is calling: FOO.shopping.init() UTIL.fire is calling: FOO.shopping.cart() UTIL.fire is calling: FOO.common.finalize()
In addition, using these classes and IDs on the body tag provides some excellent specific hooks for your CSS.
The javascript:
UTIL = { fire : function(func,funcname, args){ var namespace = FOO; // indicate your obj literal namespace here funcname = (funcname === undefined) ? 'init' : funcname; if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){ namespace[func][funcname](args); } }, loadEvents : function(){ var bodyId = document.body.id; // hit up common first. UTIL.fire('common'); // do all the classes too. $.each(document.body.className.split(/\s+/),function(i,classnm){ UTIL.fire(classnm); UTIL.fire(classnm,bodyId); }); UTIL.fire('common','finalize'); } }; // kick it all off here $(document).ready(UTIL.loadEvents);
This system worked very well and keeps you in serious control of the execution order.
In the end, I used this plus a custom event to bind super low priority script.
For example:
$(document).bind('finalized',function(){ ... }); // placed within a FOO.shopping.category()
And I'd trigger that
$(document).trigger('finalized');
at the very end of UTIL.loadEvents(). This allows you to keep similar code together, but delay portions responsibly without any setTimeout ugliness.
Follow me on twitter: @paul_irish