回到使用 ajax 的 PushState 条目
我对以下情况有疑问。
- 用户访问站点
- 用户单击使用history.pushState更新url的链接
- 通过ajax加载部分页面内容(使用jQuery)
- 用户单击加载新页面的常规链接
- 用户单击返回以返回到pushState条目
- 页面现在仅显示页面通过 ajax 检索的部分
我已经使用 PushState 增强了一个网站的各种功能,结果是一个响应速度惊人的 Web 应用程序,但这个问题阻止了我使用它。
以下是代码示例:
$('a').live('click', function(){
history.pushState({}, '', this.href);
popstate(this.href);
return false;
});
popstate = function(url){
$('#content').load(url);
}
window.onpopstate = function(event){
popstate(window.location.href);
event.preventDefault();
}
注意:
- 在 window.onpopstate 函数中放置警报时,第 5 步似乎未触发该事件。这是一个错误吗?
- 仅当使用ajax时才会出现此问题。
- 我必须分离 popstate 函数,以便我可以在 pushState 之后调用它。有没有办法手动触发window.onpopstate事件?
I'm having an issue with the following situation.
- User visits site
- User clicks link which uses history.pushState to update the url
- Partial page content loaded via ajax (using jQuery)
- User clicks regular link which loads a new page
- User clicks back to return to the pushState entry
- The page now displays only the page partial that was retrieved via ajax
I've souped up a site using pushState for various things and the result is a shockingly responsive web app, but this issue is preventing me from using this.
Here's a sample of the code:
$('a').live('click', function(){
history.pushState({}, '', this.href);
popstate(this.href);
return false;
});
popstate = function(url){
$('#content').load(url);
}
window.onpopstate = function(event){
popstate(window.location.href);
event.preventDefault();
}
Notes:
- When placing an alert in the window.onpopstate function it appears that the event is NOT triggered at step 5. Is this a bug?
- The issue only occurs when ajax is used.
- I have had to separate the popstate function so I can call it after pushState. Is there a way to manually trigger the window.onpopstate event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎有些浏览器经常混淆通过 ajax 加载的部分内容和用其布局装饰的整个页面。这是因为它们都有相同的 URL。
因此,当用户单击后退按钮时,浏览器不会加载 URL,而只会显示之前通过 ajax 下载的部分内容。
为了避免这种情况并维护两个独立的内部缓存(一个用于部分页面,一个用于整个页面),您应该在通过 ajax 调用时在 URL 中添加 GET 参数。就像你的代码中这样:
希望这有帮助。
It seems that some browsers often confuse the partial loaded via ajax and the entire page, decorated with its layout. That's because they both have the same URL.
So when the user click on the back button, the browser won't load the URL and will just display the partial it has previously downloaded via ajax.
To avoid this and maintain two separate internal caches (one for the partial page and one for the entire page), you should add a GET parameter in the URL when calling via ajax. Like this in your code:
Hope this helps.