This is a discussion on addLoadListener - adding onload event in generic way within the JavaScript Code Samples forums, part of the JavaScript Programming category; One of the most common problems with JavaScript is adding events to run in the page onload event, meaning after ...
| |||||||
|
#1
| ||||
| ||||
| 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>
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>
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! |
| The Following User Says Thank You to Shadow Wizard For This Useful Post: | ||
jmurrayhead (July 14th, 2008) | ||
![]() |
|
| Bookmarks |
| Tags |
| listener, onload |
| Thread Tools | |
| Display Modes | |
| |
| ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| On onchange event hide blank frame | guddu | JavaScript Programming | 3 | September 8th, 2008 09:14 AM |
| Generic Form Handler | richyrich | .Net Development | 3 | July 28th, 2008 01:34 PM |
| Generic Paging Class | Shem | .Net Development | 4 | July 18th, 2008 11:29 AM |
| Grouping buttons to one event | Shem | .Net Development | 8 | July 17th, 2008 06:53 AM |
| adding an event for my btnDelete in repeater | Shem | .Net Development | 13 | July 15th, 2008 09:33 AM |