Home > Web Front-end > H5 Tutorial > HTML5 study notes - History API_html5 tutorial skills

HTML5 study notes - History API_html5 tutorial skills

WBOY
Release: 2016-05-16 15:46:56
Original
1617 people have browsed it

1. Opening Analysis

Okay, without further ado, let’s go directly to today’s topic. Today we will mainly talk about the “History API” and its role in single-page applications, and will introduce a practical example as a prototype for the explanation. First Let’s take a look at the “History API”:

In order to improve the response speed of Web pages, more and more developers are beginning to adopt single-page application solutions. The so-called single-page structure means that when switching between multiple pages, the entire current page is not refreshed, the page display data is updated, and the URL in the address bar is changed accordingly so that users can share this URL.

If you use browsers such as Chrome or Firefox to access websites such as "github.com, plus.google.com", you will find that clicks between pages are requested asynchronously through ajax,

At the same time, the URL of the page has changed. And it can support browser forward and backward very well. What is it that has such a powerful function? Well, this brings us to today’s protagonist, a new API referenced in HTML5:

"history.pushState" and "history.replaceState" are used to change the page URL without refreshing through this interface. Let’s first take a look at the detailed methods of the "history" interface:


Copy code
The code is as follows:

interface History {
readonly attribute long length;
readonly attribute any state;
void go(optional long delta);
void back();
void forward();
void pushState(any data, DOMString title, optional DOMString? url = null);
void replaceState(any data, DOMString title, optional DOMString? url = null);
};

(2), key API description

One point to note here: "window.history.replaceState" is similar to "window.history.pushState". The difference is that replaceState will not add a new historical record point in window.history, and its effect is similar to window.location. .replace(url) will not add a new record point to the historical record point. The replaceState() method is particularly appropriate when you want to update the state object or URL of the current history entry in response to some user action.

(3), introduce examples

Today, let’s talk about what we usually do in single-page applications. There is a menu list, click on the relevant menu items and then dynamically load the relevant modules. All methods are based on asynchronous requests. The fly in the ointment is that we will find that the address bar will not There will be no response to any changes, as well as the forward and backward operations in the browser, which is not very user-friendly, so in order to solve this problem "History" comes into play, so how to do it? Don’t rush, first take a look at the renderings in the example, and then analyze it step by step, as shown below:

The following is the monitoring data. Refreshing the same URL will not cause repeated requests.

Let’s sort out the process:

The page is loaded for the first time. Although the URL we visited is "http://localhost:8888/bbSPA.html", the actual URL is indeed:

"http://localhost:8888/bbSPA.html#shanghai", "history.replaceState" completed the initial url switching work and did the initial loading

To work with the data of "shanghai.data", click any menu item on the left, the content on the right will be loaded by Ajax, and the URL of the page will change accordingly, for example, click on Beijing.

At this point, we click the back button on the address bar to return to Shanghai and display the content. The principle is very simple, that is, by monitoring "window.onpopstate", free switching is achieved.

Okay! In fact, it’s very simple. You can try it yourself. The following is the complete code:

 (1), html part code 


Copy code
The code is as follows:



bbSPA测试页面




id="content-main"
style="margin-left:50px;
float:left;
width:220px;
border:1px solid #ccc;
height:120px;
color:#ff3300;"
>


(2),Js部分代码


复制代码
代码如下:

$(function(){
_init() ;
}) ;
var _history = [] ; // 记录hash的活动数据容器
function _init(){
var root = $("#list") ;
var defaultHash = root.find("li a").eq(1).attr("href") ;
var currentHash = window.location.hash ;
_addToHistory(defaultHash,true) ;
if(currentHash && currentHash != defaultHash){
_showContent((currentHash.split("#")[1])) ;
}
else{
_showContent((defaultHash.split("#")[1])) ;
}
$("#list").on("click","a",function(e){
var action = ($(this).attr("href").split("#")[1]) ;
_showContent(action) ;
e.preventDefault() ;
}) ;
window.addEventListener("popstate",function(e){
if(e.state && e.state.hash){
var hash = e.state.hash ;
if(_history[1] && hash === _history[1].hash){//存在历史记录,证明是后退事件
_showContent(hash.split("#")[1].toLowerCase()) ;
}else{ // 其它认为是非法后退或者前进
return ;
}
}
else{
return ;
}
},false) ;
} ;
function _showContent(action){
var samePage = _history[0]["hash"] == "#" action ;
if(samePage){ // 同页面,则不重新加载
return ;
}
_loadContent(action ".data").done(function(data){
_renderContent(data["content"]) ;
_addToHistory("#" action,samePage) ;
}).fail(function(){
throw new Error("load content error !") ;
}) ;
} ;
function _loadContent(url){
return $.ajax({
url : url ,
dataType : "json"
}) ;
} ;
function _renderContent(text){
$("#content-main").text(text) ;
} ;
function _addToHistory(hash,noState){
var obj = {
hash : hash
} ;
if(noState){
_history.shift(obj) ;
window.history.replaceState(obj,"",hash) ;
}
else{
window.history.pushState(obj,"",hash) ;
}
_history.unshift(obj) ;
} ;
 

(四),最后总结

  (1),理解History Api的使用方式以及具体实例中使用的目的是为了解决哪些问题。

  (2),两个核心Api的不同之处在哪。

  (3),测试本例子的注意事项如下。

  测试需要搭建一个web服务器,以http://host/的形式去访问才能生效,如果你在本地测试以file://这样的方式在浏览器打开,就会出现如下的问题:


复制代码
代码如下:

Uncaught SecurityError: A history state object with URL 'file:///C:/xxx/xxx/xxx/xxx.html' cannot be created in a document with origin 'null'.

  因为你要pushState的url与当前页面的url必须是同源的,而file://形式打开的页面是没有origin的,所以会报这个错误。

以上就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template