Onload Conflicts

I've noticed that this topic comes up frequently at the forums, so I wrote this little article. (this is just a rough draft so far)

It is common for scripts to need to be initialized when the page is first loaded by the browser. Here are three different ways a function can 'listen' for the window onload event.

  1. Assign a string to the onload attribute of the opening body tag.
  2. Assign an anonymous (un-named) function to window.onload.
  3. Assign a reference to an existing, named function.

Here are a few things to look for when using different scripts in the same page.

  1. Look at the opening body tag in the html file. Does it assign anything to the onload attribute?
  2. Search all your html and js files for "onload". Is anything assigned to window.onload? Is there more than one assignment?

If there is more than one assignment to onload in the body tag or in any javascript then you have found a conflict. For example, the following has such a conflict.

<html>
<head>
<script type='text/javascript'>

// Menu script (could be in a separate file).

window.onload = function()
{
  // Menu initialization statements.
}

// Animation Script (could be in a separate file).
// Initialization statements are in function initAnimation().

window.onload = initAnimation;

</script>
</head>
<body onload="preloadImages('...', '...')">
...
</body>
</html>

In the above there are three initialization tasks that need to be accomplished when the document first loads (the window.onload event). The following is a typical solution to the above conflict.

<html>
<head>
<script type='text/javascript'>

// If the browser doesn't support what our scripts need
// then we 'downgrade' by not listening for the onload event.

if ((document.getElementById || document.all) && document.images) {
  window.onload = windowOnload;
}

function windowOnload()
{
  menuOnload();
  initAnimation();
  preloadImages('...', '...');
}

function menuOnload()
{
  // Menu initialization statements.
}

</script>
</head>
<body>
...
</body>
</html>

The solution was developed by taking the following steps.

  1. Copy then delete any assignment to the onload attribute in the opening body tag.
  2. Paste the code copied in step 1 into your custom onload listener. In my example it is called windowOnload.
  3. Is there any place in the javascript where an anonymous function is assigned to window.onload (for example the menu initialization code in the first code listing)? If so, copy those statements into another function (for example menuOnload above). Call that function from windowOnload.
  4. Is any reference to an existing function assigned to window.onload (for example the animation initialization)? If so, call that function in windowOnload.

Cross-Browser.com