最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Jan 11, 2021 at 10:58 AkashAkash 8382 gold badges12 silver badges31 bronze badges 2
  • Does this answer your question? How to create a vanilla JS routing for SPA?. Express doesn't do client-side routing. – ggorlen Commented Jan 30, 2022 at 19:41
  • Check this out: youtube./watch?v=mWeJnl9Ixxs – Nishan Commented Apr 24, 2024 at 5:45
Add a ment  | 

1 Answer 1

Reset to default 6

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 ponent/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./#/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./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./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!

发布评论

评论列表(0)

  1. 暂无评论