HTML5 learning notes-History API, html5 learning notes

Source: Internet
Author: User

HTML5 learning notes-History API, html5 learning notes
This series of articles mainly focus on Html5-related knowledge points, taking Learning API knowledge points as the entrance and introducing instances from a simple perspective, so that you can understand what "h5" can do step by step, and how to use it properly in actual projects to achieve ease of use, and to perfectly control O (strong _ strong) O ~,

I. Opening Analysis

Well, let's talk a little bit about it. Let's go directly to today's topic. Today we mainly talk about "History API" and Its Role in single-page applications, A practical example will be introduced as a prototype example. Let's take a look at "History API ":

To improve the response speed of web pages, more and more developers begin to adopt a single-page application solution. The single page structure means that when switching between multiple pages, the current whole 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 the url.

If you use chrome or firefox to access "github.com, plus.google.com" and other websites, you will find that the clicks between pages are requested asynchronously through ajax,

At the same time, the page URL has changed. In addition, the browser can be well supported to move forward and backward. What is so powerful? Well, this will talk about the main character of today. HTML5 references the new API:

"History. pushState" and "history. replaceState" are implemented through this interface without refreshing the page URL. Let's take a look at the detailed methods of the "history" interface:


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 descriptions

It is explained here: "window. history. replaceState "and" window. history. pushState "is similar. The difference is that replaceState does not exist in the window. A New Historical Record Point is added in history. The effect is similar to window. location. replace (url) does not add a new record point in the Historical Record Point. The replaceState () method is especially suitable when you want to update the status object or URL of the current history record in response to some user operations.

(3) Introduce instances

Today, we usually do this in a single-page application. There is a menu list, click the relevant menu items, and then dynamically load the relevant modules. All methods are based on asynchronous requests, we will find that the address bar will not change, and the browser's forward and backward operations will not have any response, which is not very friendly to users, so to solve this problem, "History" is useful. How can this problem be solved? Do not rush to take a look at the example and analyze it step by step, as shown below:

The following are monitoring data. Refresh the same url without repeated requests.

Let's sort out the process:

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

"Http: // localhost: 8888/bbSPA.html # shanghai", "history. replaceState" Completes url initialization and loading.

For "shanghai. data" data operation, click any menu item on the left, the content on the right is Ajax loading, and the URL of the page changes accordingly. For example, click Beijing.

At this point, we click the back button in the address bar and return to Shanghai, and the content is displayed. The principle is very simple, that is, by listening to "window. onpopstate", the function of free switching is achieved.

Okay! In fact, it is very easy for everyone to practice it by themselves. The following is the complete code:

(1) Some html code


The Code is as follows:
<Body>
<Center>
<Strong> bbSPA test page </strong>
</Center>
<Hr>
<Ul
Id = "list"
Style = "float: left;
List-style: none ;"
>
<Li> <a href = "# beijing"> beijing </a> </li>
<Li> <a href = "# shanghai"> shanghai </a> </li>
<Li> <a href = "# shenzhen"> shenzhen </a> </li>
<Li> <a href = "# guangzhou"> guangzhou </a> </li>
<Li> <a href = "# tianjin"> tianjin </a> </li>
</Ul>
<Div
Id = "content-main"
Style = "margin-left: 50px;
Float: left;
Width: 220px;
Border: 1px solid # ccc;
Height: 120px;
Color: # ff3300 ;"
>
</Div>
</Body>

(2) JavaScript code


The Code is as follows:
$ (Function (){
_ Init ();
});
Var _ history = []; // The Active Data container that records the 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) {// a historical record exists, proving to be a back event
_ ShowContent (hash. split ("#") [1]. toLowerCase ());
} Else {// others think it is illegal to move back or forward
Return;
}
}
Else {
Return;
}
}, False );
};
Function _ showContent (action ){
Var samePage = _ history [0] ["hash"] = "#" + action;
If (samePage) {// same page, no reload
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 );
};
 

(4). Conclusion

(1) understand how to use the History Api and the problems used in specific instances.

(2) Where are the differences between the two core APIs.

(3) Note the following when testing this example.

To test the function, you must build a web server and access it in the form of http: // host/. If you test the function locally and open it in the browser in the form of file, the following problems may occur:


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

Because the url of the pushState must be the same as the url of the current page, and the page opened in the file: // format does not have the origin, this error is reported.

The above is all the content of this article. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.