MPAs that feels like SPA
npm i waystone
yarn add waystone
pnpm add waystone
import 'waystone';
NOTE: Waystone is required to only run once, so it's ideal to serve it on JS files where the module is going to be instanciated once.
You can use ws:replace
to replace the History state rather than push when navigating
<a href="/my-page" ws:replace>My page</a>
By default, anchor tags will scroll up instantly to the top of the page when navigated to. You can add ws:scroll="none"
to preserve scroll or you can use ws:scroll="smooth"
if you want the page to scroll up smoothly.
You can add one of the following attributes to your anchor tags prefetch strategies:
ws:animation-frame
: Prefetches throughrequestAnimationFrame
ws:delay="1000"
: Prefetches throughsetTimeout
ws:idle
: Prefetches throughrequestIdleCallback
ws:interaction
: Prefetches when the element receives focus, is hovered or about to be touched.ws:load
: Prefetches after the current window has loaded.ws:media="(orientation: portrait)"
: Prefetches using media queryws:ready-state="interactive"
: Prefetches usingdocument.readyState
ws:visible
: Prefetches when the element is visible in the viewport
You can add ws:disabled
to your anchor element.
<a href="/my-page" ws:disabled>My Page</a>
Waystone provides lifecycle events through on
.
import { on } from 'waystone';
on('unload', () => {
cleanupStuff();
});
Waystone lifecycle involves three steps:
beforeunload
: This is called beforeunload
happens. In this event, you can cancel the navigation by callingevent.preventDefault()
on('beforeunload', (event) => {
const prompt = window.confirm('Are you sure you want to leave?');
if (!prompt) {
event.preventDefault();
}
})
unload
: This is called before the document is replaced.load
: This is called after the document is replaced.
Please use with caution!
By default, waystone replaces the entire page when navigating to a new one, which means that every element from the previous page would get disposed. If you want to skip elements that are similar from the previous page (or any page), you can add ws:diff
to your <html>
.
<html ws:diff>
...
</html>
ws:diff
utilizes morphdom
and DOMParser
.
The difference, however, would be:
- Scripts will no longer run on the new page.
window
'sDOMContentLoaded
andload
events wouldn't work.
MIT © lxsmnsyc