I had to manage an array of functions (with parameters), and execute them when onload event fires.
I know I could use jQuery's $(window).load()
, but we all know that to reduce page loading time, every js script (jquery, jquery plugins, ...) must be inserted at page bottom, just before </body>
.
Therefore the only js I'm loading in <head>
is this:
var fn_chain = [];
function addFn2Load(fn) {
if(typeof fn != 'function')return;
fn_chain.push(fn);
}
function doLoad() {
for(var i=0,iL=fn_chain.length;i<iL;i++) {
fn_chain[i]();
}
}
if (window.addEventListener) {
window.addEventListener("load", doLoad, false);
} else if (window.attachEvent) {
window.attachEvent("onload", doLoad);
} else if (window.onLoad) {
window.onload = doLoad;
}
Then I can push functions in my array from everywhere in the page, without the need of loading jQuery first. I just write
addFn2Load(function() {
foo(arg1, arg2, argN);
bar(arg1, arg2);
$("#myElementId").myCoolPlugin(); // I can use $ even if jQuery is not loaded yet
});
My solution simply works... Could some javascript guru tell me if I'm doing it right? Is it improvable?