Uses XHR/Ajax to create dynamic transitions when a user navigates from one page to another. This allows for seamless transitions between page changes.
npm install @joinbox/dynamicpageloaderLoads content of a web page dynamically when the user navigates to a different URL. It thereby
enables seamless page transitions between two different static web pages, similar to the ones
provided by Next.js or Gatsby.
Supports:
- Elements that are preserved in the DOM when the page changes (data-preserve-id)
- Hook to test if the given URL should be loaded dynamically
- Hook to execute a script before the page content is changed (e.g. for animations)
- Hook to execute a script after the page content was changed (e.g. for animations)
- Only adds dynamic click handler to elements once (to not fire url change multiple times for
elements that are preserved over a page change)
There are certain limitations concerning the use of JavaScript, as the global scope is preserved
over page loads:
- Don't use any global variables or functions, especially not consts (would throw an already
declared error). Use IFFEs e.g. where
appropriate.
- Don't use type="module" script tags for code that should be executed on page load. Module
script tags will only execute when the page is initially loaded.
Be aware that CSS is handled differently:
- The sort order of elements will not be adjusted to the element order of the new page,
as moving elements around causes flickering.
```javascript
import {
applyChanges,
handleLinkClicks,
handlePopState,
loadFile,
createNode,
canBeIdentical,
isIdentical,
applyAttributes,
} from '@joinbox/ui-components/DynamicPageLoader';
// Prevents loading of a new page when a link is clicked. Uses pushState to update the URL
// displayed by the browser instead and emits 'urlchange' event that will be handled later.
handleLinkClicks({
// In this case, we hijack all clicks on regular links
linkElements: document.querySelectorAll('a'),
// Limit the links that are hijacked; in this case, only use dynamic page loader for absolute
// links (on current domain)
checkLink: link => link.startsWith('/'),
});
// Handles navigation through the back button and emits 'urlchange' event if the previous page
// was loaded dynamically.
handlePopState();
// Add event listener to 'urlchange' event that was fired above. Handle URL change with a smooth
// transition instead of a hard page load.
window.addEventListener(
'urlchange',
async(ev) => {
const { url } = ev.detail;
const dom = await loadFile(url);
// If you like, add some nice animations here.
//