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 realize simple single page application SPA with PushState+Ajax

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you how to achieve a simple single-page application SPA by PushState+Ajax. The content is concise and easy to understand, which can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Single page application (Single Page Application) is referred to as SPA. The application built with SPA has the advantages of good user experience and high speed. The change of content does not need to reload the entire page, avoiding unnecessary jump and repeated rendering, thus relatively reducing the pressure on the server. SPA is widely used in WEB mobile.

Today I would like to introduce to you the use of HTML5 PushState+ajax not to refresh the entire page, but the address bar transformation, page local refresh effect, integrated front and back page technology to achieve a simple SPA. Let's first learn about a few knowledge points.

HTML5 History API

HTML5 adds the pushState method to History, which adds the current url to the history, and then modifies the current url to the new url. Of course, this method only changes the Url display of the address bar, but does not make any requests. Therefore, we can use this method combined with ajax to achieve a single page application SPA, that is, PushState+Ajax, known as Pjax.

How to use pushstate:

History.pushState (state, title, url)

State: you can put any data you want, and it will be attached to the new url as a supplement to the information on the page.

Title: as the name implies, it is document.title.

Url: the new url, which is the url you want to display on the address bar.

History.replaceState (state, title, url)

The replaceState method is more or less the same as pushState, except that pushState adds the current url to the history and then modifies the url, while replaceState simply modifies the url without adding the history.

_ window.onpopstate

In general, the popstate event is triggered whenever the url changes. However, if pushState is called to modify the url, this event will not be triggered, so we can use it as a forward and backward event for the browser. This event takes one parameter, which is the first parameter state of the pushState method above.

What can Pjax do?

Pjax is an excellent solution that can do:

You can make a smooth transition between pages and add Loading animation. You can pass data between pages without relying on URL. You can selectively retain the state, such as a music website, and do not stop playing songs when you switch pages. All tags can be used to jump, not just the a tag. It avoids the repeated execution of the public JS, reduces the request volume, saves traffic, and speeds up the page response. There will be no impact on SEO, and for browsers that do not support HTML5 and search engine crawlers, you can jump to real pages. Support for browser forward and back buttons.

Realization principle

1. Intercepts the default jump action for the a tag.

two。 Use Ajax to request a new page.

3. Replace the returned Html into the page.

4. Use HTML5's History API or Url's Hash to modify Url.

Code implementation

HTML

We set up a menu # nav and load the contents of the linked page into p#result by clicking the link on the menu.

Home products and services

Pjax.js

First, determine the browser's support for html5 in pjax.js, and then define a cache cache object: cache {}, and define the methods to set cache and get cache. Then define the event event object: event {}, bind popstate and hashchange as well as the click event, and the click event triggers a call to the pajax object to request page content. Cache cache object and event event object code you can download the source code to view, this article due to space reasons only the core pjax {} object code glued out.

Var pjax = {/ / Forward And Back, indicating whether the current operation is triggered by forward and backward fnb: false, / / displays the new page content show: function (title, html) {document.title = title; document.querySelector ('# result') [xss_clean] = html }, / / Jump to the specified page jump: function (url, data, callback) {/ / if triggered by forward and backward, try to get data from the cache if (pjax.fnb) {var value = cache.get (url); if (value! = = null) {pjax.show (value.title, value.html); return;}} document.querySelector ('# result') [xss_clean] = 'loading..' / / ajax send request var xhr = new XMLHttpRequest (); xhr.open ("GET", url, true); xhr.setRequestHeader ("X-PJAX", "true"); xhr.setRequestHeader ("X-PJAX-TITLE", data); xhr.setRequestHeader ("X-Requested-With", "XMLHttpRequest") Xhr.onreadystatechange = function () {if (xhr.readyState = 4) {if (xhr.status > = 200 & & xhr.status < 300 | | xhr.status = = 304) {/ / 304is the cache var html = xhr.responseText, title= xhr.getResponseHeader ("X-PJAX-TITLE"); if (title==null) {title= document.title;} else {title= decodeURI (title);} / console.log (title); / / display the new page pjax.show (title, html) / / not the forward and backward buttons trigger if (! pjax.fnb) {/ / modify the URL,URL address bar to transform if (support = = 'HTML5') {history.pushState (null, null, url);} else {var path = url.replace (location.protocol + "/" + location.host, "); location.hash = path;} / / add to the cache cache.set (url, {title: title, html: html}) }} else {console.log ('request failed!') ;} pjax.fnb = true;}; xhr.send ();}, init: function () {event.bindEvent ();}}

As you can see, the core of pjax is to send asynchronous ajax requests, call the history.pushState () method of html5, cache page information, and already process the results returned by asynchronous requests.

Finally, call:

Pjax.init ()

The above is how PushState+Ajax implements a simple single-page application SPA. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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: 0

*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