根据惯例,我将所有代码放在$(document).ready中,但是我的“popstate”监听器也应该放在代码的最后吗?或者这很重要吗?
根据惯例,我将所有代码放在$(document).ready中,但是我的“popstate”监听器也应该放在代码的最后吗?或者这很重要吗?
这并不是很重要,而且由于它是一个事件,甚至可以在你的ready
方法之前执行。唯一需要放置在document ready
中的是与DOM交互的代码。其他所有内容都不需要(可能也不应该)放置在document ready中。
例如:
window.onpopstate = function() {
// binding this event can be done anywhere,
// but shouldn't be inside document ready
};
$(document).ready(function() {
// DOM manipulation and other stuff
});
实际触发popstate事件的时间与其绑定时大不相同。根据Mozilla文档:
每次激活历史记录条目更改时,都会向窗口分派一个popstate事件。如果要激活的历史记录条目是通过调用history.pushState()创建的或者受到调用history.replaceState()的影响,则popstate事件的state属性包含历史记录条目状态对象的副本。
document.ready
将jQuery
别名为$
(例如jQuery(function($){...code...});
),那么你需要使用匿名函数来进行别名操作:(function($){...code...})(jQuery);
- zzzzBovhttps://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
调用history.pushState()
或history.replaceState()
不会触发popstate事件。只有在执行浏览器操作(例如单击后退按钮(或在JavaScript中调用history.back()
)时),才会触发popstate事件,当在同一文档的两个历史记录条目之间导航时。所以在 Chrome(和显然是 Safari)中,jquery 的 ready 方法将被执行,然后是 popstate 事件。 也就是说,无论您在 ready 中附加事件(或者在 body.onload 中),popstate 事件都会在 ready 方法完成后发生。浏览器在处理页面加载时通常会以不同的方式处理 popstate 事件。 Chrome 和 Safari 总是在页面加载时发出 popstate 事件,但 Firefox 不会。
onpopstate
并非所有浏览器都支持:http://caniuse.com/#search=history - Matt