domFunction | JavaScriptSource


James Edwards Feb 26, 2007


An easy-to-use snippet, that allows other DOM scripting to run before window.onload. The practical benefit is that JavaScript doesn't have to wait for images or other dependencies to finish loading. It can begin as soon as the DOM is ready.


The link to the script can go anywhere, but if it's going to call other functions it must come after them in the source code. Then use the object constructor to define individual functions. You can either call a named function:

var foobar = new domFunction(myFunction);

Or write an anonymous function directly inside the constructor:

var foobar = new domFunction(function() {
	 //code ...

The function will be called once the DOM is ready (determined by the existence of the getElementsByTagName method and the presence of the <body> element; this is the point at which you can safely use DOM methods, including creating and appending new elements to the <body>).

You can treat it essentially the same as a regular onload function except that - if you're going to manipulate (e.g., read from or append to) any existing HTML elements other than the body, you must also test for those elements before calling your script.

And for this purpose the constructor takes an optional second argument - an object-literal which defines the elements or collections that the script should test before trying to call the function:

var foobar = new domFunction(function() {
	//code ...
}, { 'poster' : 'id', 'h1' : 'tag' });

Each name/value pair should be either:

  • the ID of an element, followed by the value "id", to test whether that element exists; or
  • the tag name of an element, followed by the value "tag", to test whether that collection has any members.

Source Code

Paste this source code into the designated areas.

External file

Paste this code into an external JavaScript file named: domFunction.js


Paste this code into the HEAD section of your HTML document.

Leave a Response