


How to create a history record in javascript without reloading the page (code)
The content of this article is about how JavaScript can create a historical record (code) without reloading the page. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
Background
Recently while working, I encountered such a requirement. In a multi-page application, the same data source needs to be shared on several pages, and Switching pages does not refresh the page data, and can realize the backward function of history records; because in the early stage, only the effect of realizing multiple pages in one page was considered, and the processing in the history stack was not considered, resulting in the page being pushed out of the entrance at once. Several solutions are summarized below.
hash
In the URL, # is called the location identifier, which represents a location on the web page. When we first came into contact with the a tag, many of us Everyone has operated anchor point jump, mainly through href Set the ID value of the location you want to jump to. During this process, the page is not refreshed, but a new history record is added; we can use window.location.hash to obtain the hash value of the current page, and at the same time You can also write a new hash value through it and detect whether the hash value has changed by listening to the hashchange event. When we click on the pop-up mask page, we can manually modify the value of location.hash, so that by clicking window.history.back(), we can roll back the history;
Example
The code is as follows:
nbsp;html> <meta> <title>Title</title> <style> body{ background: #ccc; } .colorBlock { border: 10px solid #fff; height: 40vh; width: 40vh; margin: 20vh auto 10vh; color: #ffffff; font-size: 40px; line-height: 40vh; text-align: center; } .colorBlue{ border: 10px solid #fff; height: 40vh; width: 40vh; margin: 20vh auto 10vh; color: #ffffff; font-size: 40px; line-height: 40vh; text-align: center; background: cornflowerblue; } .colorgray{ border: 10px solid #fff; height: 40vh; width: 40vh; margin: 20vh auto 10vh; color: #ffffff; font-size: 40px; line-height: 40vh; text-align: center; background: lightcoral; } .colorgreen{ border: 10px solid #fff; height: 40vh; width: 40vh; margin: 20vh auto 10vh; color: #ffffff; font-size: 40px; line-height: 40vh; text-align: center; background: greenyellow; } .btnBlock{ text-align: center; } .btn{ border: 5px solid #ffffff; font-size: 24px; line-height: 50px; width: 40vh; } </style> <div> 加载中.... </div> <div> <button>change-url</button> </div> <script> ( function () { var a=0; setInterval(function () { a++; document.getElementById("content").innerText=a; },1000) } )() window.addEventListener("hashchange",function (e) { var now=location.hash && location.hash.substring(1); switch (now){ case "blue": document.getElementById("content").setAttribute("class","colorBlue"); break; case "gray": document.getElementById("content").setAttribute("class","colorgray"); break; case "green": document.getElementById("content").setAttribute("class","colorgreen"); break; } },false); document.getElementsByClassName("btn")[0].addEventListener("click",function () { var now=location.hash && location.hash.substring(1); if(now=="blue"){ location.hash="gray" document.getElementById("content").setAttribute("class","colorgray"); }else if(now=="gray"){ location.hash="green" document.getElementById("content").setAttribute("class","colorgreen"); }else if(now=="green"){ location.hash="blue" document.getElementById("content").setAttribute("class","colorBlue"); } },false); </script>
Open the page in the browser and add #blue to the route, as follows:
You can see the following page. Under initial conditions, the display of the page is loading..., and then the timer triggers an update and displays the increasing number. At this time, we can in the console Print out the corresponding history.length, its value is 2:
## Re-enter window.history.length on the console to see, Its value has changed to 3. Click the browser back arrow and the page background changes to the previous blue background. At this point, we have achieved the function we want;
In addition to the methods mentioned above, the same effect can also be achieved through the new history.pushState in html5;
history.pushState Both history.replaceState and history.replaceState are new APIs in HTML5. Both can change the URL of the status bar without refreshing the page. However, the difference between the two is that replaceState replaces the current address with the specified URL, while pushState creates a new one. historical record. The window.onpopstate event will be triggered after executing history.back() and history.forward().history.pushState(state,title,url)
state: object, which can store some data to represent the current state. When the browser executes forward or backward, the onpopState event will be triggered. The state will be the attribute object of the event object and can be accessed through event.state; it should be noted that the attribute value in statez cannot be an object. url is the address to be replaced; if it is puhState, a history record will be added;We can also use the above example to test, but, we What needs to be monitored is the popstate event, create a new history record, and save the current information to history.state.
history.pushState && window.addEventListener("popstate",function(e){}) history.pushState && history.pushState(state,title,url)Summary
The two methods introduced above can be used On the premise that the page does not jump, you can modify the URL and add a new history record, and you can perform forward and backward operations through the browser's default text. However, it should be noted that the two monitor different response events that trigger the modification. And the way to modify the url is also different.
The above is the detailed content of How to create a history record in javascript without reloading the page (code). For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment