Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

routes - Routing in a single page app(spa) without framework, just javascript

I am trying to make a Single Page Application using html, css and javascript. I would like to add some routing to it. I have made server-side rendered websites with nodejs and express. How do I create a routing system for my SPA? Can we use express for client-side routing? If not, are there any alternatives to express for client side routing?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you don't want to use a framework/library for building a SPA, you have two options

  1. Use a JS routing library ex: navigo, didn't try it myself TBH
  2. 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:

  1. 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
  2. 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...