Navigation
When writing MPAs and the page load is slower than expected, you maybe want to show a page-load-in-progress indicator. This can be done easiest by using the "navigate" event of the Navigation API just
- use
navigation.addEventListener('navigate', ...)to act when the user navigates away from the page (to a page that may load slowly) - show some page-load indicator (spinner, progress bar, etc.)
What does PicoSPA do here? Actually nothing, but the file navigation.js provides a polyfill for browsers
that do not support the Navigation API yet. If you are on a modern browser you just keep using the Navigation API as is.
And feel free to use this page here to learn about some possible use cases and/or how to use it.
How To Use
Add the script to your page and call restore with a unique page key:
<script src="https://cdn.jsdelivr.net/npm/@pic0/spa@2026.1.12/_dist/picospa.min.js"></script>
PicoSPA loads the polyfill for the navigate event if needed.
Examples
Basic Example
The following is not useful at all, but shows the use case very well.
Copy this into your developer console to see it in action:
navigation.addEventListener('navigate', () => alert('navigating away!'));
When the user navigates away from the page an alert is shown, this one has the side-effect of blocking the navigation until the user clicks "OK".
Disable the Submit Button the user clicked
A more useful example is to disable the submit button the user clicked, to avoid double submits:
<form action="/some-slow-endpoint" method="post" id="my-form">
... your form fields here ...
<button type="submit" id="submit-button">Submit</button>
</form>
<script>
const submitButton = document.getElementById('submit-button');
navigation.addEventListener('navigate', (event) => {
if (event.sourceElement === submitButton) {
// disable the button to avoid double submits
submitButton.disabled = true;
// optionally change the button text
submitButton.textContent = 'Submitting...';
}
});
</script>
This examples uses the event.sourceElement property of the navigate event
to check
if the submit button was clicked, and if so disables it and changes its text content.