HTML5 history API改变浏览器地址无需hash和刷新加载页面技术
现在很多网站的前端做的非常炫,点击某个链接瞬间改变浏览器的地址栏的地址,改变的方式不是使用锚点,而是直接改变 URL,页面稍后局部加载完成。如果直接复制页面地址在新的浏览器选项卡中打开则是全部加载整个页面。这样的前端技术体验,一开始让我和很多的前端工程师觉得现有的知识不可能做到。后来才了解到,在一般的比较老的浏览器中是不可能实现的,需要在 Chrome, Safari, FF4+, and IE10pp4+ 才能做到!。
最开始发现这样的效果是在 GITHUB 中,后来看到很多同行的技术博客也有使用了这样类似的技术的。我问过一个做前端的同事,问他的网站的这样的技术是怎么实现的,他告诉我说是使用锚点;我说,锚点是有“#”号的,但是我并没有看到“#”号啊;他说,那个“#”号是可以隐藏的。之前也了解过这样的技术,大概知道是 HTML5 history 相关的 API 可以实现,当他告诉我使用隐藏锚点时,我顿时感觉很奇怪,于是才写了这篇文章。
最简单的实现,代码如下:
<script> window.history.pushState("object", "ignored param title", "/this_is_new_url"); </script>
本文下面做了两个临时改变页面地址体验的按钮,下面的 button 控制了点击次数,防止创建了太多的 history 栈,下面的按钮点击了改变再恢复后,您会发现您的浏览器出现了可以前进的按钮。
有关 pushState 方法,developer.mozilla.org 有详细的描述,第一个参数是一个 JavaScript 对象关联到新创建的历史实体,第二个参数暂时没有什么用处,第三个参数是新的 URL。原文如下:
The pushState() method pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail: state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object. The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage. title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving. URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
另一个重要的 HTML5 API,onpopstate 方法。该方法在浏览器前进后退时被触发。用来侦测 pushState 或 history.back(),可以在此处做一些局部刷新或修改标题的操作。如下代码示例:
<script> // You can then use window.onpopstate to detect the back/forward button navigation: window.onpopstate = function(e){ if(e.state){ document.getElementById("content").innerHTML = e.state.html; document.title = e.state.pageTitle; } }; </script>
相关文章
暂无