Safari <body onload> event doesn't trigg

2019-03-06 15:51发布

问题:

I don't seem to be able to get the body onload="..." event to fire in Safari when the page is entered via the back button. It works fine in FF and IE. Is there a Javascript or jQuery solution?

Any help appreciated.

回答1:

Try:

window.addEventListener("pageshow", function() {
  alert('page shown');
}, false);

For Opera browser, read this: http://samuli.hakoniemi.net/onload-issues-with-opera/



回答2:

This is well known. Safari and many other browser cache the page and when you navigate back to it, they just restore the previous state.

Here is a good MDN article about this topic (it's about FF 1.5 but should apply to other browsers as well): https://developer.mozilla.org/En/Using_Firefox_1.5_caching

Try the pageshow event like @zvona suggested.



回答3:

if the onload event is not fired,you should set the cache-control.

<head>
<meta charset="utf-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">

or add a tag in the body:

<iframe style=”height:0px;width:0px;visibility:hidden” src=”about:blank”>
this frame prevents back forward cache
</iframe>


回答4:

Rather than using the onload attribute of the <body> tag, you could instead try using the DOM ready event with jQuery, like so:

$(document).ready(function() {
    // your code here
});

Or, the shorthand version:

$(function() {
    // your code here
});

Even if this doesn't solve your issue with Safari, it's still a good practice in general because it separates your HTML and Javascript into easily discernible parts.