I have a HTML page and a javascript function is attached to the <body>
onLoad event.
I wanted to show up a message dialog when the page loads. I cannot edit the javascript function attached to this onLoad event due to some reasons.
So I created a new javascript file with a single function which will show the message dialog. Then I added this line in my javascript file
window.onload = onPageLoad;
onPageLoad()
is my function which could show the message dialog.
I attached this javascript file in my HTML using script tag. When I run this HTML file, onPageLoad()
function is not getting called.
I want to know whether <body>
tag, onLoad event overrides the window onload. If so, can someone help me in implementing this functionality somehow.
Please keep in mind that I could not edit my HTML file and I could write only new javascript file. Thanks.
document. onload event is fired before the window. onload.
The main differences between the two are: Body. Onload() event will be called only after the DOM and associated resources like images got loaded, but jQuery's document. ready() event will be called once the DOM is loaded i.e., it wont wait for the resources like images to get loaded.
Unfortunately, you cannot place multiple onload events on a single page. You can nest multiple functions within the one onload call, but what if you need to cascade an onload script across multiple pages, some which may already have an existing onload event? use the addLoadEvent function below.
The $(document). ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded.
Depends on browser. window.onload currently overwrites body onload in Chrome, Firefox and Safari on OSX
You can ADD your function to the onload:
window.onload = function() {
alert('window.onload')
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>
AND/OR Replace
var bodyOnload = document.body.onload;
window.onload = function() {
alert('window.onload')
bodyOnload()
}
if (window.addEventListener) {
window.addEventListener('load', function() {
alert('addEventListener')
}, false);
} else if (window.attachEvent) { // IE < 9
window.attachEvent('onload', function() {
alert('attachEvent')
});
}
<body onload="alert('body onload')">
</body>
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