If you don't want to use a framework/library for building a SPA, you have two options
- Use a JS routing library ex: navigo, didn't try it myself TBH
- Build it by yourself
To build your own simple SPA Routing, first, you need to:
- Define routing config, each path with the relevant component/element/content to load
- Define your routing root, the element where you will inject the content
Then you have two options:
- Use # Hash paths (ex: domain.com/#/messages) with window popstate event, so you can handle this event by getting the hash path and decide which content to inject in the root, check this answer for more details about his approach
- Implement a custom routing with normal paths (ex: domain.com/messages), that needs more effort, and to achieve that you need to:
- Implement your custom navigation links, where you need to prevent the default behavior of navigation, and do the navigation manually using your custom logic
- Use History API, (ex. pushState) to control the location state and the history stack
- Adjust your server config to always load index.html
- Add your custom logic using the Location API to manage these redirects manually, ie. when a user opens domain.com/messages, it will open index.html, then you need to check manually what the content to load for /messages path and inject it in the root element
Please be aware of the needed time, effort, reliability, maintainability, of each option before starting!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…