Aja Lapus: Blogging with Standards

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!

2 Responses to “Stacking Script Event Loaders”

  1. 1

    *nosebleed* hehe

    Jaypee posted on 6 November 2008, 03:32

  2. 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 ;)

    Gel posted on 6 November 2008, 19:16

Post another response »

Leave a Reply

Reply guidelines: Only the XHTML elements <a href="" title="">, <abbr title="">, <acronym title="">, <blockquote cite="">, <code>, <em> and <strong> are allowed. Line breaks and paragraphs are automatically generated. I am using a comment spam filter. Don't fret if your replies do not appear right away—don't repeatedly submit them. I have the right to remove or edit comments I feel inappropriate for my site.

Copyright and Publication Information

Copyright © 2005–2008, Aja Lorenzo Lapus. All rights reserved.
All content are properties of Aja Lorenzo Lapus unless stated otherwise.