Whilst developing our latest component ‘IP Mapper’ I encountered a problem that is possibly known to many but not previously to me.  For that reason decided to make this blog entry.

I was generating javascript code which made a call at the end to the ‘window.load event’.  The code worked perfectly when it was only present once.  However when present more than once only the last call actually worked.

Why did I need it more than once?  Well the code was generated for a specific module, and because the modules could each have very different parameters specified, I had to tailor the javascript for each specific module hence the slightly different code, but each has a different ‘window.onload event’ function call.

I discovered this post by Robert Hahn which describes a solution which I have implemented.

The solution:

function makeDoubleDelegate(function1, function2) {
    return function() {
        if (function1)
            function1();
        if (function2)
            function2();
    }
}
window.onload = makeDoubleDelegate(window.onload, myNewFunction );
Works a treat.