How can I run a JavaScript code when the page loads without using the onload
tag?
I'm trying to run this script:
<script type="text/javascript">
function displayLightbox() {
document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'
}
</script>
That displays a lightbox.
Like this:
window.onload = function WindowLoad(event) {
alert("Page is loaded");
}
Edit: if some other code is also using window.onload
after that script then it will be "overwritten" - to make sure it's executed (and abort any other onload
) put it in the bottom of the page.
Edit 2: On second thought, you better add onload listener instead of overwriting it:
<script type="text/javascript">
if (window.addEventListener) { // Mozilla, Netscape, Firefox
window.addEventListener('load', WindowLoad, false);
} else if (window.attachEvent) { // IE
window.attachEvent('onload', WindowLoad);
}
function WindowLoad(event) {
alert("Another onload script");
}
</script>
This will prevent any conflicts with existing code and is more cross browser as far as I can tell.
Live test case is available here: http://jsfiddle.net/yahavbr/GZPTG/ tested for IE8, Chrome and Firefox (latest versions) feel free to test for more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With