Generic onload

Version 1.1 - 1st November 2004

This script is an encapsulated onload function that doesn't interfere with other window.onload or <body onload> functions on the same page. The script works in all modern browsers (with javascript enabled).

The demo uses alert() dialogues to demonstrate the onload methods firing. If scripting (or this script) is not supported, nothing will happen.

Get the script

Download the zipfile [1K] and unzip it into your site directory, then you can either include the script on your page as it is:

<script type="text/javascript" src="onload.js"></script>

or copy the code into another script, and work with it from there:

//GO1.1 :: Generic onload by brothercake -

//onload function
function generic()
    alert('Generic onload function');

//setup onload function
if(typeof window.addEventListener != 'undefined')
    //.. gecko, safari, konqueror and standard
    window.addEventListener('load', generic, false);
else if(typeof document.addEventListener != 'undefined')
    //.. opera 
    document.addEventListener('load', generic, false);
else if(typeof window.attachEvent != 'undefined')
    //.. win/ie
    window.attachEvent('onload', generic);

//** remove this condition to degrade older browsers
    //.. mac/ie5 and anything else that gets this far
    //if there's an existing onload function
    if(typeof window.onload == 'function')
        //store it
        var existing = onload;
        //add new onload handler
        window.onload = function()
            //call existing onload function
            //call generic onload function
        //setup onload function
        window.onload = generic;

There may be limitations on where this can go, depending on the level of browser support you need ...

Browser notes

Mac/IE5 doesn't support any truly encapsulated onload methods, so the script has to use window.onload. But it does this with sensitivity - if your page is already using a window or <body onload> handler, the script will copy and call that first, before the generic onload kicks in.

It can only do this if the handler has already been defined, therefore this script must come after it in the source-code, or the generic onload won't be called.

You can of course simplify your life, and just remove the final else{} condition - degrading Mac/IE5 and older browsers to unsupported. Then it won't matter where the script is, or how many of them them you use.

Get the script

BSD License → Terms of use



Parts for other scripting:

Website gadgets

Bits of site functionality:

Usability widgets

Local network apps

Web-applications for your home or office network:

Game and novelties

Our internal search engine is currently offline, undergoing some configuration changes in preparation for a major site overhaul. In the meantime, you can still search this site using Google Custom Search.

In this area

Main areas

[brothercake] a round peg in a square hole, that still fits