One of the most common problems with JavaScript is adding events to run
in the page onload event, meaning after the page finished loading.
Here is function that solve lots of headache:
Code:
<script type="text/javascript">
function addLoadListener(fn) {
if (typeof window.addEventListener != "undefined")
{
window.addEventListener("load", fn, false);
}
else if (typeof document.addEventListener != "undefined")
{
document.addEventListener("load", fn, false);
}
else if (typeof window.attachEvent != "undefined")
{
window.attachEvent("onload", fn);
}
else {
var oldfn=window.onload; if (typeof window.onload != "function") window.onload = fn; else window.onload = function() { oldfn(); fn();}
}
}
</script>
how to use?
like this:
Code:
<script type="text/javascript">
function FirstFunc()
{
alert("hello I'm first");
}
function SecondFunc()
{
alert("hello I'm second");
}
addLoadListener(FirstFunc);
addLoadListener(SecondFunc);
</script>
this will activate
both functions.. ordinary code would overwrite
the previous onload and trigger only the latest.
note: the order of execution might differ among different browsers.
for example in IE, it's LIFO (Last In First Out, meaning the second function
above will get executed before the first) and in Firefox it's FIFO - First In
First Out, meaning the first will be first and second is the second.
yes, I know you're not surprised.
Happy Programming!