开发者

will HTML <body> onLoad events overwrite javascript window onload event?

I have a HTML page and a javascript function is attached to the <bod开发者_Python百科y> 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.


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>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜