Stacking Script Event Loaders

I’ve been playing around with JavaScript once when I’ve encountered a problem about my scripts not working, especially those attached to event handlers. You could probably see JavaScript declarations like this on a script or another:

window.onload = functionName;

And, soon, I found out that a lot of plugins I have use the same declaration for initializing their scripts. So, I looked for references and realized that they overwrite one another by declaring that assignment operation over and over again. Looking for solutions, I came across two possible ways to do it:

  1. if (typeof window.onload != 'function') {
    	window.onload = newOnLoadFn;
    } else {
    	var onLoadStack = window.onload;
    	window.onload = function() {
    		onLoadStack();
    		newOnLoadFn();
    	}
    }
  2. var onLoadStack = window.onload;
    window.onload = function() {
    	if (typeof onLoadStack == 'function' && onLoadStack) {
    		onLoadStack();
    	}
    	newOnLoadFn();
    }

Coding preferences applies, as either basically does the same effect of stacking window.onload events. You could put them on a function if you must:

function addOnLoadEvent(newOnLoadFn) {
	if (typeof window.onload != 'function') {
		window.onload = newOnLoadFn;
	} else {
		var onLoadStack = window.onload;
		window.onload = function() {
			onLoadStack();
			newOnLoadFn();
		}
	}
}

And call events using:

addOnLoadEvent(
	// declaration of function type
);

I would recommend anyone distributing scripts to make use of this to avoid conflicts with other event-triggered scripts users may have beside yours. Thanks!


Comments

2 responses to “Stacking Script Event Loaders”

  1. *nosebleed* hehe

  2. Your post made me go “WUHHH?!?!?!!!” Hahaha I could NOT relate but i’m sure it’s very informative to people can actually relate with it 😉