If you deal with more than external JavaScript file on a web page, it is only a matter of time before you run into a problem with window.onload. If two scripts each use window.onload, then the first function gets overwritten by the second.

The Problem

Most scripts need to wait until the document is ready to start performing duties. Often, window.onload is used to guarantee that the document is ready to be manipulated with JavaScript. Using 2 or more scripts with window.onload , however, cause the first to be overwritten.

JAVASCRIPTview code
// the common start to many scripts
window.onload = function() { ... }

The Solution

A few weeks ago, I wrote an article on adding events without overwriting any existing events. The same principle will be used here.

What you want to do is always look for an existing onload function and save it for later. In fact, it requires only 2 new lines of code. This simple solution needs no framework and is completely unobtrusive. You do code unobtrusively, don’t you?

  • Step 1- assign old window.onload into a variable
  • Step 2- check if is a function and execute inside the new event

Solid Tip: Put this code only in the second file. If you put it in both, it will cause a recursion error.

The Example

JAVASCRIPTview code
var existing = window.onload;
 
window.onload = function() {
 
    if(typeof(existing) == "function"){ existing(); }
    /* your other code here */
 
}

Solid Tip: You can put step 2 before or after your other code to meet your needs.