Preface
When you think of routing, you usually think of libraries like react. But in reality, these libraries and frameworks still use vanillaJavaScript. So how to achieve it?
I hope this "JavaScript Routing Tutorial" can help you understand how to write your own routes in native js.
Introduction
I've met a lot of people who want to create their own routes for a variety of reasons. Since you have seen this article, it means you may be one of them too!
Most importantly, using vanillajsrouter can reduce your dependence on the framework.
As long as you understand all the parts involved in implementing it, it can be relatively easy to create your own route in native JavaScript.
Here are the key things to know when making your own JS router:
1. The key to native JS routing is attributes.
2. Listen to the "popstate" event in response to changes in .pathname. This happens whenever we enter a new URL into the address bar of the browser, but we don't want to refresh the page, we just want to refresh the view by loading new content.
3. You can choose to store the routes in the routes[] array.
4. JavaScript regular expressions must be used (RegEx) can resolve the URL.
5. A basic understanding of history and (JavaScript's History API) is crucial if you want to integrate routing into your native browser architecture.
First, we will deal with the History API.
JavaScript's History API
I've seen a lot of things that don't mention the JavaScript History APIvanilla JS routerTutorial. Too bad, because clicking the Back and Forward buttons of your browser is related to URL navigation in your browsing history. Without the History API, you can't talk about routing.
() is the same as (-1), or when the user clicks the Back button in the browser. You can achieve the same effect in either way.
2. When the user presses the Forward button of the browser, () will be executed, which is equivalent to (1)”.
() is similar to the .back() and forward() methods, the difference is that you can specify the number of steps to go forward or backward in the browser history stack. .
() will push the new status to the History API.
5..length attribute is the number of elements in the session history.
6..state attribute is used to find state without listening for "popstate" events.
Implement your own native JS routing
Vanilla JS routing settings based on History API
Let's first look at the minimum code required to build a URL switcher (Without refreshing the page) and I'll show you the GIF animation of how it works.
<html> <head> <title>Hello</title> <script type = "module"> function select_tab(id) { // remove selected class from all buttons (".route").forEach(item => ('selected')); // select clicked element (visually) ("#" + id).forEach(item => ('selected')); } function load_content(id) { // Update text "Content loading for {id}..." // Of course, here you would do you content loading magic // Perhaps run Fetch API to update resources ("#content").innerHTML = 'Content loading for /' + id + '...'; } function push(event) { // Get id attribute of the box or button or link clicked let id = ; // Visually select the clicked button/tab/box select_tab(id); // Update Title in Window's Tab = id; // Load content for this tab/page loadContent(id); // Finally push state change to the address bar ({id}, `${id}`, `/page/${id}`); } = event => { // Add history push() event when boxes are clicked window["home"].addEventListener("click", event => push(event)) window["about"].addEventListener("click", event => push(event)) window["gallery"].addEventListener("click", event => push(event)) window["contact"].addEventListener("click", event => push(event)) window["help"].addEventListener("click", event => push(event)) } // Listen for PopStateEvent (Back or Forward buttons are clicked) ("popstate", event => { // Grab the history state id let stateId = ; // Show clicked id in console (just for fun) ("stateId = ", stateId); // Visually select the clicked button/tab/box select_tab(stateId); // Load content for this tab/page loadContent(id); }); </script> <style> * { /* global font */ font-family: Verdana; font-size: 18px; } #root { display: flex; flex-direction: row; } #content { display: flex; display: block; width: 800px; height: 250px; /* vertically centered text */ line-height: 250px; border: 2px solid #555; margin: 32px; text-align: center; } .route { cursor: pointer; justify-content: center; width: 150px; height: 50px; /* vertically centered text */ line-height: 50px; position: relative; border: 2px solid #555; background: white; text-align: center; margin: 16px; } . { background: yellow; } </style> </head> <body> <section id = "root"> <section class = "route" id = "home">/home</section> <section class = "route" id = "about">/about</section> <section class = "route" id = "gallery">/gallery</section> <section class = "route" id = "contact">/contact</section> <section class = "route" id = "help">/help</section> </section> <main id = "content">Content loading...</main> </body> </html>
The core is right ({id}, ${id}, /page/${id}); call;
The first parameter is the unique ID of the state, the second is the "tag title" text, and the third parameter is the path you want to realistic in the address bar. This is why the browser changes the URL without reloading the page.
result. Now, every time we click the button, the URL will actually change in the browser's address bar. The content box will also be updated.
Our native JS route is running. Note that each time the button is clicked, it is triggered. We just need to pass the id of the clicked element stored in the id attribute of the element to it: home, about, gallery, etc. They should be consistent with the actual page you want to navigate to. Of course this is not the only way to store page names, for example, you can use array [] or any other way. This is how to operate in this example.
Of course we also need to load content about the layout and resources of the location from the server. It depends on your program. It can be anything.
Make the Back and Forward buttons work
By using, you will automatically make the Back and Forward buttons navigate to the previous or next state. Doing so will generate a popstate event. This is the part where you have to update the view again. (The first time we clicked the button。)
But since the event comes with a clicked id, it's easy to refresh the view and reload the content when clicking Back or Forward.
We are not using react or vue here, so load_content in my source code will be responsible for updating the view directly in the DOM. This area may be filled with something loaded by your API. Since this is just a "front-end" example, I can't show you much. But that's itClienton how to work.
Initialize the server-side routing load
Putting them together requires another step. In my case, it was only used. When you first load this route in a PWA, you must make sure it works if you enter /page/home directly in the address bar.
So far, we onlyfront endChange the router address. Assume that every time you navigate to the URL that appears on the routing button, the URL will actually be loaded separately from the server.
Therefore it is your responsibility to make sure /page/about load the router and pages into the root view of the application. It should also highlight the "current" button.
After the implementation is completed, your route is completed. How you choose to reload the content in the #content element depends entirely on yourself and your backend design.
The above is the detailed content of how to make your own native JavaScript route. For more information about making native JavaScript routes, please follow my other related articles!