memories

Do you remember the days of jquery, when the big three front-end frameworks were not popular and front-end developers were frantically checking jquery API documentation for DOM manipulation? (For front-end history, see this article: front-end technology development juejin.cn/post/684490…

I remember when I first started to write web pages in school, I only learned a general knowledge of JavaScript, and then I started to learn jquery for web development.

If you’ve ever been a jquery developer, the water in your glass started to shiver when you saw this code. My youth!

At that time, I only used jquery to write front-end for half a year after graduation, without the engineering, modularization and componentalization provided by these front-end frameworks. (Actually, there is, but I haven’t learned it yet. Moreover, I was the first front-end of the company at that time, without the guidance of predecessors, I explored by myself.) Write front-end use JS (jquery), CSS, HTML, to carry out the construction of the project file directory structure. How tired IT was to think of that time!

primers

When I was writing a web page, I met a need:

If a page has several navigation links on the left and content on the right, and only the content on the right needs to be updated during navigation, then refreshing the entire page is undoubtedly wasteful. At this point we can use AJAX to pull the data on the right. But if only this, the address bar will not change, the user can not move forward, backward, also can not bookmark the current page or share the current page to others; Search engine crawls also have difficulty.

At this point, check out HTML5’s History API to solve the problem.

Ideas:

  • First bind the click event. PreventDefault when users click on a link, prevent the default behavior with preventDefault, read the link’s address ($(this).attr(‘href’ if jQuery is available), pushState it into the browser history, Use AJAX techniques ($. Get if you have jQuery) to pull the actual content of the address and replace the content of the current page.

  • To handle users moving forward and backward, we listen for popState events. When the user clicks the forward or back buttons, the browser address is automatically converted to the corresponding address and a POPState event occurs. In the event handler function, we grab the corresponding content according to the current address, and then use AJAX to pull the real content of the address, rendering, and then.

  • Finally, the entire process does not change the page title, which can be changed by assigning document.title directly.

The code looks something like this:

window.history.pushState(null.null."/profile/");
Copy the code

Simple application of the History API

PushState method

The API provides a way to “artificially manipulate” the browser history.

Browser history can be thought of as a “stack.” A stack is a last-in, first-out structure, which can be thought of as a stack of plates. Each time a user clicks on a new web page, a new plate is added to it, called “pushing”. Each time the user clicks the Back button, the top plate is removed, called “out of the stack.” Each time the browser displays the contents of the top plate.

var state = {
    id: 2.name: "profile"
};
window.history.pushState(state, "My Profile"."/profile/");
// It can accept three arguments, in order:
// 1. An object or string that describes some properties of the new record. This parameter is also added to the history for later use. This parameter is freely given by the developer according to their own needs.
// 2. A string representing the title of the new page. This parameter is currently ignored by almost all browsers.
// 3. A string representing the relative address of the new page.
Copy the code

Popstate event

The PopState event is triggered when the user clicks the browser’s Forward and Back buttons. You can listen to the incident and react.

window.addEventListener("popstate".function(e) {
    var state = e.state;
    // do something...
});
// where e.state is the first argument passed to pushState. For example, in our example, there are:
// e.state.id == 2;
// e.state.name == "profile";
Copy the code

ReplaceState method

Sometimes, if you want to replace the current record instead of adding a new one (such as the landing page of a website), you can use the replaceState method. This method is identical to the argument to pushState.

Simple hash application for Location

A hash is also a way to change the browser URL without refreshing the page

The function of #(hash) in the URL

1. Anchor point positioning

The “#” represents a location in the web page. The character to the right is the identifier for that position

Such as: juejin. Cn/post / 684490…

When the browser reads the URL, it automatically scrolls to the comment location area.

There are two ways to specify an identifier for a web page location.

  • One is to use anchor points
<a name="comment"></a>
Copy the code
  • The second is to use the ID attribute
<div id="comment"></div>
Copy the code

So when we use it without specifying an identifier, the page doesn’t get positioned, but we get what we want by changing the browser URL without refreshing the page

2.HTTP requests do not include data after ‘#’

The ‘#’ is used to direct browser action and is completely useless on the server side. Therefore, # is not included in the HTTP request.

For example, visit the following website, juejin.cn/post/684490… If we open F12 and check the network’s all, we find that #comment does not take into account the score

3. Changing # changes the browser’s access history

History is the browser’s history, location is the browser’s current URL information (hash is the value), and they are apis provided by the browser BOM

Onhashchange event

This is a new HTML 5 event that is triggered when the # value changes.

function hashHandler() {
  console.log('The hash has changed! ');
}

window.addEventListener('hashchange', hashHandler, false);
Copy the code

The front-end routing

This piece of content is looking for online articles, online information is a lot, learned two juejin.cn/post/684490… Juejin. Cn/post / 684490…

1. What is front-end routing

The concept of routing originated from the server. In the past, when the front and back ends were not separated, the back end controlled routing. When receiving the HTTP request from the client, it would find the corresponding mapping function according to the corresponding URL requested, and then execute the function and send the return value of the function to the client. For the simplest static resource server, you can think of the mapping function of all urls as a file read operation. For dynamic resources, the mapping function may be a database read operation, some data processing, and so on. Then according to these read data, the server side will use the corresponding template to render the page, and then return the rendered page. Its advantages and disadvantages are obvious:

  • Benefits: good security, SEO;
  • Disadvantages: increase the server pressure, is not conducive to user experience, code redundancy is not good maintenance;

It is because of the shortcomings of back-end routing that front-end routing has its own development space. For front-end routes, the route mapping function usually does some DOM show and hide operations. In this way, different page components are displayed when accessing different paths.

2. What is SPA

SPA stands for Single Page Web Application.

Simply speaking, SPA is a WEB project with only one HTML page. Once the page is loaded, SPA will not reload or jump the page because of the user’s operation. Instead, JS is used to dynamically transform HTML content to simulate multiple view jumps.

3. Go from traditional pages to SPA views

  • In traditional web design, each HTML file is a finished HTML page, covering the complete HTML structure.
  • In the application design of SPA, an application has only one HTML file, and the HTML file contains a placeholder (container in the figure), and the corresponding content of the placeholder is determined by each view. For SPA, the switching of pages is the switching between views.

4. Route implementation

Front-end routing is not a new technology, we just use the name of the route used by the back end, which is actually a wrapper around the browser’s hash model and history mode (each front-end framework encapsulates its own route, we refer to the documentation and use the rules).

So once we know the browser’s hash and history, we can see something that we thought was amazing before.

We don’t make the wheel, but we need to know the purpose and meaning of the wheel, based on what principle. If you are interested in this wheel, you can read the source code and learn the code ideas and design patterns, but don’t make another one based on what you already have.

If you want to learn about some simple encapsulation of routing, click on the two post addresses and learn about it. In-depth study of the three framework routing source code, their own fumble.