如何应对使用JS历史API pushState刷新页面 [英] How to cope with refreshing page with JS History API pushState

查看:117
本文介绍了如何应对使用JS历史API pushState刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建的一个小网站(更像是小提琴)使用AJAX加载每一页。以前我正在更改网址的哈希,这很好但很难看,用户可以刷新页面,它会保留在同一页面上。



现在我已经切换到在JS History API中使用pushState,它看起来好多了,后面和前面的工作,但刷新没有。例如:



转到: http://example.com/page2 转到404,因为有没有真正的页面调用第2页。但是如果我点击使用pushState方法更改网址的按钮,它就可以正常工作。



如何允许刷新,和新历史API永久链接?



(以及搜索引擎如何对待这一点,因为谷歌必须创建一种索引哈希网址的方法,让开发人员切换到#!,是否有可能他们会为将来的历史api做类似的事情?)

解决方案

您不应该使用 pushState 来推送无效的URL。这意味着在网站同时使用和不使用AJAX的情况下使用 - 即,当您使用AJAX创建此输出时,您推送的网址不会导致AJAX输出相同。



如果您只想要虚拟URL(例如在pushState时代之前),请继续使用哈希标记。


A small website I was creating (more like fiddling) uses AJAX to load each page. Previously I was changing the hash of the url, this worked great but was ugly, and the user could refresh the page, and it would stay on the same page.

Now I have switched to using pushState in the JS History API, which looks much better, and the back and forward work, but refreshing does not. For example:

Going to: http://example.com/page2 goes to a 404 as there is no real page called page 2. But if I click on the button which uses the pushState method to change the url, it works as it should.

How can allow refreshes, and permalinks with the new History API?

(And how do search engines treat this, seeing as Google had to create a way of indexing hash urls, by making the developer switch to #!, is it possible they will do something similar for the history api in the future?)

解决方案

You shouldn't use pushState to push invalid URLs at all. It's meant to be used in cases where the site works both with and without AJAX - i.e. you push the URL which would result in the same output without AJAX when creating this output with AJAX.

If you want only virtual URLs (like in the pre-pushState era), keep using the hash tag.

这篇关于如何应对使用JS历史API pushState刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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