History API / Routing

SPA

(Single Page Application)
SPA
web application hosted on a single page that loads all javascript files (modules, widgets, controls, etc.) and CSS files along with loading the page itself to make it work
API History and Routing are help implement the SPA principle in native Javascript
History API

The DOM Window object provides access to the browser's session history (not to be confused for WebExtensions history) through the history object. It exposes useful methods and properties that let you navigate back and forth through the user's history, and manipulate the contents of the history stack.
Window.history
  • back() - to move backward through history
  • forward() - similarly, you can move forward (as if the user clicked the Forward button)
    go()
  • to move forward a page, just like calling forward() if added argument 1
  • just like calling back() if added argument -1
  • If added argument 0 page is will reload
  • If added (argument > 1) if (argument <1) you can move forward or backward in pages by the number of pages specified by the argument
  • history.pushState(state, title[, url]) - in an HTML document, the method adds an entry to the browser's session history stack
  • history.replaceState (state, title[, url])- remove an entry to the browser's session history stack
  • history.length() - return history stack length
addEventListener('popstate', (event) => { }) - popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript)
Routing
A router is a JavaScript object that maps URLs to functions. The router calls a function based on the URL. In the past, a web application was a series of interconnected pages. This could either be static pages or dynamic pages that are generated on the server.
Example of creating a route

					
				
Create server.js

					
				
Create index.html

									
														
								
						
					
Create main.js

					
				
Add to main.js

					
				
Add to main.js
to create an array of buttons
with "router" attribute

					
				
Adding listener to buttons navigate

					
				
Function for rendering
HTML template elements

						
					
The End