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.
// 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
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.
Many Thanks. It worked for me.
My pleasure!
Thx 😀 good job
But i did get a problem…
First file copy the code.
Second file i copy the code without var existing = window.onload;
It didn’t work for me.. the event form the second overwrite the event from the first file.
So i add var existing = window.onload; in the second file and of course it still didn’t, it overwrithe it :P. Change from existing to existing2 and now it works, for me
gr.
The code should be used in the second file and the first should be left alone. I have updated the article with a Solid Tip above to specify that. Thanks!
Also, if you need to use it for a 3rd file, simple add the code and change
existing
toexisting2
or some other name.It worked for me with JavaScript errors but the functions work in ie and Firefox browsers. I wrapped this snippet on my second function.
thank you so much!
m
I searched everywhere for this. By far the best, most simple way to do this. I was pulling my hair out using other bits of code that I had seen elsewhere.
Cheers, Mr. Stated 🙂
My pleasure, thanks!
is this possbile with jQuery ? jQuery(function(){
and how?
gr.