单击后退按钮时是否存在跨浏览器onload事件? [英] Is there a cross-browser onload event when clicking the back button?

查看:149
本文介绍了单击后退按钮时是否存在跨浏览器onload事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于所有主流浏览器(IE除外),当页面因后退按钮操作而加载时,JavaScript onload 事件不会触发 - 它仅在以下情况下触发该页面首次加载。

For all major browsers (except IE), the JavaScript onload event doesn’t fire when the page loads as a result of a back button operation — it only fires when the page is first loaded.

有人能指出我解决这个问题的一些示例跨浏览器代码(Firefox,Opera,Safari,IE,...)吗?我熟悉Firefox的 pageshow 事件,但不幸的是Opera和Safari都没有实现这一点。

Can someone point me at some sample cross-browser code (Firefox, Opera, Safari, IE, …) that solves this problem? I’m familiar with Firefox’s pageshow event but unfortunately neither Opera nor Safari implement this.

推荐答案

伙计们,我发现JQuery只有一个效果:当按下后退按钮时会重新加载页面。这与准备好无关。

Guys, I found that JQuery has only one effect: the page is reloaded when the back button is pressed. This has nothing to do with "ready".

这是如何工作的?好吧,JQuery添加了一个 onunload 事件监听器。

How does this work? Well, JQuery adds an onunload event listener.

// http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { // ...

默认情况下,它什么都不做。但不管怎么说,这似乎会触发Safari,Opera和Mozilla的重载 - 无论事件处理程序包含什么。

By default, it does nothing. But somehow this seems to trigger a reload in Safari, Opera and Mozilla -- no matter what the event handler contains.

[编辑(Nickolay):这就是为什么它的工作原理: webkit.org 开发人员.mozilla.org 。请阅读这些文章(或我在以下单独答案中的摘要),并考虑您是否真的需要这样做,并使您的页面加载速度慢于您的用户。

[edit(Nickolay): here's why it works that way: webkit.org, developer.mozilla.org. Please read those articles (or my summary in a separate answer below) and consider whether you really need to do this and make your page load slower for your users.]

不能相信吗?试试这个:

Can't believe it? Try this:

<body onunload=""><!-- This does the trick -->
<script type="text/javascript">
    alert('first load / reload');
    window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>

使用JQuery时会看到类似的结果。

You will see similar results when using JQuery.

您可能希望与没有 onunload

<body><!-- Will not reload on back button -->
<script type="text/javascript">
    alert('first load / reload');
    window.onload = function(){alert('onload')};
</script>
<a href="http://stackoverflow.com">click me, then press the back button</a>
</body>

这篇关于单击后退按钮时是否存在跨浏览器onload事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆