Automatically initialising Javascript objects that require the DOM

One of the problems I had when I first started creating Javascript widget objects is that I always needed to create the object in two stages. First I’d actually create an object with the correct parameters, then I’d register a piece of script that actually did all of the initialisation code that accessed the DOM to run after the page had finished loading to do things like registering events.

This meant that the script for using my object ended up in two places in the page so eventually I figured out a way to make the initialisation stage of object setup run automatically.

  1. function MyObject()
  2. {
  3.     create();
  4.     /*
  5.     * This method is run as after the javascript include is parsed.
  6.     * It registers an initialisation method to run when the page has finished loading.
  7.      * We can't actually do any initialisation that requires the DOM in this method
  8.      * because we can't be sure if the elements we want to use have been loaded yet.
  9.      */
  10.     function create() {
  11.         // if this is something that understands DOM methods
  12.         if(window.addEventListener) {
  13.             // register the initialise method to run when the window has finished loading
  14.             // in the DOM compliant way
  15.             window.addEventListener("load", initialise, false);
  16.         } else if(window.attachEvent) {
  17.             // else register the initialise method to run the IE way
  18.             window.attachEvent("onload", initialise);
  19.         }
  20.     }
  21.     /*
  22.     * This method is run when the page has finished loading.
  23.      * It is now safe to access any part of the page, get pointers to important DOM
  24.     * objects and register events.
  25.      */
  26.     function initialise(e) {
  27.         // make sure this browser is DOM compliant
  28.         if(document.getElementById) {
  29.             // run any initialisation code here
  30.         }
  31.     }
  32. }
Posted on 23 Nov 04 by Helen Emerson (last updated on 23 Nov 04).
Filed under Javascript