Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use History API

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use History API". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use History API.

First, the opening analysis

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

If you use browsers such as chrome or firefox to visit 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 can well support the browser forward and backward. What has such a powerful function? Well, when it comes to today's protagonist, the new API is quoted in HTML5:

"history.pushState" and "history.replaceState", it is through this interface to change the page URL without refresh. Let's first take a look at the detailed method 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 description

Note here: "window.history.replaceState" is similar to "window.history.pushState", except that replaceState will not add a new history point to window.history. Its effect is similar to _ window.location.replace (url). It will not add a new record point to the history point. The replaceState () method is especially appropriate when you want to update the status object or URL of the current history entry in response to some user actions.

(3) introduce an example

Today, when we talk about single-page applications, we usually do this: there is a menu list, click on the relevant menu items and then dynamically load the relevant modules, all of which are based on asynchronous requests. The only drawback is that we will find that there will be no change in the address bar and no response to forward and backward operations in the browser, which is not very user-friendly. So in order to solve this problem, "History" has the opportunity to use its talents, so how do you do that? Take a look at the illustration in the example first, and then analyze it step by step, as shown below:

The following is the monitoring data. The same url refresh will not repeat the request.

Let's sort out the process:

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

"http://localhost:8888/bbSPA.html#shanghai","history.replaceState" completed the initialization of the url switch and initially loaded

"shanghai.data" data work, the mouse clicks any menu item on the left, the content on the right is loaded by Ajax, and the URL of the page changes accordingly, for example, click on Beijing.

At this point, we click the back button in the address bar, go back to Shanghai, and display the content. The principle is very simple, that is, by listening to "_ window.onpopstate", to achieve the role of free switching.

Okay! In fact, it is very simple for everyone to try to practice it on their own. Here is the complete code:

(1), html partial code

The code is as follows:

BbSPA Test Page

Beijing

Shanghai

Shenzhen

Guangzhou

Tianjin

(2), Js partial code

The code is as follows:

$(function () {)

_ init ()

})

Var _ history = []; / / record the active data container of 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) {/ / has a history record and is proved to be a fallback event

_ showContent (hash.split ("#") [1] .toLowerCase ()

} else {/ / others consider it illegal to retreat or advance

Return

}

}

Else {

Return

}

}, false)

}

Function _ showContent (action) {

Var samePage = _ history [0] ["hash"] = = "#" + action

If (samePage) {/ / same page, do not 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) the final conclusion

(1) understand how History Api is used and what problems are used in specific examples.

(2) what is the difference between the two core Api.

(3) the considerations for testing this example are as follows.

The test needs to set up a web server and access it in the form of http://host/ to take effect. If you open the local test in a browser like file://, the following problems will occur:

The code is as follows:

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

Because you want the url of pushState and the url of the current page must be homologous, and the page opened in file:// form does not have origin, this error will be reported.

Thank you for your reading, the above is the content of "how to use History API", after the study of this article, I believe you have a deeper understanding of how to use History API, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 226

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report