YIXUNFE / blog

文章区
151 stars 25 forks source link

妙用history.state做无刷页面切换 #45

Open yvesluo opened 8 years ago

yvesluo commented 8 years ago

在AJAX风风火火的年代,大家都有尝试过用制作无刷新切换页面视图的应用。方法也不复杂,一般是通过修改location.hash来种入标识,然后使用hashchange事件来侦测标识的变化,之后AJAX加载和标识相应的内容,最后使用JS渲染出新的页面视图。本文想要讨论的是新近浏览器提供的API。这个API包括:history.state,history.pushState,history.replaceState,window.onpopstate。

history.state

浏览器在当前URL下给出的一个状态信息。如果没有使用history.pushState,history.replaceState触动过时,为默认值null

history.pushState(state, title, url)

在history中,当前的url之后加入一个新的state和url, 在浏览器上看到页面不刷新。

state:与要跳转到的URL对应的状态信息。

title:页面标题,很多浏览器都会忽略此参数。

url:要跳转到的URL地址,不能跨域。

history.replaceState(state, title, url)

在history中,用一个新的state和url替换当前的, 在浏览器上也不会造成页面刷新。

state:与要跳转到的URL对应的状态信息。

title:页面标题,很多浏览器都会忽略此参数。

url:要跳转到的URL地址,不能跨域。

window.onpopstate

history.go和history.back(包括用户按浏览器历史前进后退按钮)触发,并且页面无刷的时候(由于使用pushState修改了history)会触发popstate事件,事件发生时浏览器会从history中取出URL和对应的state对象替换当前的URL和history.state。通过event.state也可以获取history.state。

工作示意图

t1n9rzfdddxxbzie3x-1200-900

从上图可以看出,这个API在做无刷新加载,切换页面提供了可以替代HASH的方法, 思路上可以简单地理解为:

history.state = hash onpopstate = onhashchange

通过onpopstate侦测history.state的变化,来指引JS做加载,渲染等任务。

另外,history.state的好处在于可以用浏览器历史前进后退按钮触发变化,比较适应用户对浏览器历史的使用习惯。

兼容性

history state

一些参考文档

W3C html5 history:http://www.w3.org/TR/html5/history.html Introducing the HTML5 History API:http://dev.opera.com/articles/view/introducing-the-html5-history-api/ Manipulating the browser history:https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history Detecting HTML5 Features:http://diveintohtml5.org/detect.html window.history:https://developer.mozilla.org/en/DOM/window.history window.onpopstate:https://developer.mozilla.org/en/DOM/window.onpopstate MooTools onhashchange:http://yearofmoo.com/onhashchange/

joyful2 commented 2 years ago

指出一个小纰漏:pushState方法并不会触发popstate事件