Some javascript sugar

November 19, 2008

There's a really common bit of boilerplate javascript code I find myself using all the time. Basically, I'll have a function that, becuase it manipulates the DOM, needs to be called after the page has loaded. Rather than having to assign these functions to the window.onload event manually, I was looking for a shorter way.


function someFunction() {
	//Do some things with the DOM to initialize a page.
}
if (document.observe) {
	document.observe("dom:loaded", someFunction);
}
else {
    Event.observe(window, 'load', someFunction; });
}

If you use Prototype you'll recognize Event.observe, but if not, it's basically the same as this:


var loadFunctions = [someFunction];
window.onload = function() {
    for (var i = 0; i < loadFunctions.length; i++) {
         loadFunctions[i]();
    }
}

Wouldn't it be nice, I thought, to be able to do something like this?


someFunction.callOnLoad();

Well, it's pretty easy with Prototype (and jQuery, I might add). Put this in your global javascript library, if you've got one:


Object.extend(Function.prototype, {      
	callOnLoad: function(scope) {
		var fn = (scope) ? this.bind(scope) : this;
		if (document.observe) document.observe("dom:loaded", fn);
		else Event.observe(window, 'load', fn);
	}
}

Then you can just call callOnLoad as a method of any function. And if you really want to get fancy:


var MyObject = {
	
	'isInitialized': false,
	'init': function() {
		//Do some initialization of the DOM
		this.isInitialized = true;
	}
}
MyObject.init.callOnLoad(MyObject);

Tagged with: , .

Leave a comment:

Comments are closed for this entry.