How to add a body on load function with Javascript

This is an article on how to add a javascript function that will be run when a web page has loaded. We begin by defining a function for running after a page (or actually window) has been loaded:

function bodyOnLoad() {
  ..
  ..
}

And then we'll do:

window.onload = bodyOnLoad;

However, we also want to make sure our setting of the load event doesn't remove some other setting. This is done by also keeping any older events.

We store the previous on load event by doing;

var prevOnLoad = window.onload;

And we redefine our bodyOnLoad function:

function bodyOnLoad() {
  prevOnLoad();
  ..
  ..
}

However, we can make the creation of the function and the setting of the event a little bit more effective by doing:

window.onload = function() {
  prevOnLoad();

  ..
  ..
}

You still need to get prevOnLoad before you do that

This becomes even more obvious once we create a function for adding new load events:

function addLoadEvent(func) {
  var prevOnLoad = window.onload;
  window.onload = function() {
    prevOnLoad();
    func();
  }
}

In this way, we can concentrate on creating the new load event outside of the function for adding it to the window.onload.

function myEvent(){
  ..
  ..
}
addLoadEvent(myEvent);

We might even do:

addLoadEvent(
  function (){
    ..
    ..
  }
);

Notice the difference between curly braces "{}" and parenthesis "()"

Finally, we have to make sure there is a load event set for the window before calling it from the new event, so we need to check for this:

function addLoadEvent(func) {
  var prevOnLoad = window.onload;
  if (typeof prevOnLoad != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      prevOnLoad();
      func();
    }
  }
}