'Why would I use history.pushState isntead of location.hash?
There are a number of issues with pushState for an SPA:
- The web server must be specially configured to respond with the SPA index.html for any of the application routes.
- Assets and routes share the same space, causing confusion. A typo isn't an easily-debuggable 404 response, it's a 200 "OK" with HTML.
- The index.html is cached by browsers separately for every route the user arrives on, rather than once for all routes.
Whereas the URL fragment seems a logical fit for SPA routing, and solves all of these issues.
However, I notice that pushState is increasingly more common; obviously there must be some factors I'm not considering.
When/why should I consider using pushState()?
Solution 1:[1]
Here are some advantages of using the pushstate:
- Urls without hashes just look better (ok, it's a matter of taste maybe);
- You push both a url and (optional) data which enables you to restore the state of your application without doing a new request for data;
- A user can use the standard forward and back buttons of the browser to go back and forth in your app (assuming you handle things well) which you could consider as a consistent experience... ;
- ... and you can provide custom forward and back buttons and call
history.back()orhistory.forward()orhistory.go(-1)orhistory.go(+1)
When going back and forth, you can use
window.addEventListener('popstate', e => { /* code that uses e.state and location.pathname */ })
to restore things.
Then, indeed, there is the issue of having to return a single html page for each url that is not an actual asset.
One way to resolve this is to put the assets elsewhere (let's say on a CDN or assets.yourdomain.com) so your appdomain only has the return one single html file. Okay, when creating a SPA, you probably also want to be a PWA and have to return the manifest and serviceworker from the same domain where the app html is coming from so you may still end up with two exceptions but they are not very likely to conflict with your routing urls.
Another way is using tools like WebDevServer (https://modern-web.dev/) or Webpack (https://webpack.js.org/) which provide ways (history fallback api) to return a standard html for non-existing assets/resources.
Hope this helped in making some sense of the pushstate.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
