Safari <body onload> event doesn't trigger from the back button

喜你入骨 提交于 2019-12-02 22:10:12

问题


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:


This was the only thing that worked for me:

http://jkoder.com/prevent-safariany-browser-loading-from-cache-when-back-button-is-clicked/

window.onpageshow = function(event) {
  if (event.persisted) {
      window.location.reload(); 
  }
};



回答5:


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.



来源:https://stackoverflow.com/questions/9227433/safari-body-onload-event-doesnt-trigger-from-the-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!