Click a link on this site and the page doesn’t reload. The content fades out, the next page fades in, and the header never blinks. That’s Swup, a small library that fetches the next page in the background and swaps one part of the document for the new one.
Setting it up is about twenty lines. It took a good deal longer to find everything it quietly broke. This post covers both, because the second half is the part nobody mentions in the quick-start.
The Setup
A block theme makes this easy, because every template already has the same shape. There’s a header template part, a main element, and a footer. Swup only needs to know which element to replace.
import Swup from 'swup';
import SwupHeadPlugin from '@swup/head-plugin';
import SwupBodyClassPlugin from '@swup/body-class-plugin';
const swup = new Swup({
containers: ['main'],
animationSelector: 'main',
plugins: [
new SwupBodyClassPlugin(),
new SwupHeadPlugin({ persistAssets: true }),
],
});The two plugins matter on WordPress. The body class plugin copies the new page’s body classes across, and a lot of WordPress CSS hangs off those (single-post, page-id-12, logged-in). The head plugin updates the title, the meta tags and any stylesheets the new page needs.
The animation itself is CSS. Swup adds is-animating to the html element while it works, so the whole effect is one rule.
main {
transition: opacity 0.25s ease, transform 0.25s ease;
}
html.is-animating main {
opacity: 0;
transform: translateY(1.5rem);
}I only start Swup when the visitor hasn’t asked for reduced motion. Everyone else gets ordinary page loads, which are fine.
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!reduced && window.history.pushState) {
// new Swup(...)
}1. Your Scripts Only Run Once
This is the big one. Anything you set up on DOMContentLoaded runs for the first page and never again, because there’s no second page load. Scroll reveals, copy buttons and filters on the next page are all dead.
The fix is to split your script in two. One function sets up things that live for the whole visit, like the menu. The other sets up whatever is inside main, and it runs on the first load and again after every swap.
const initPage = () => {
// everything inside main: reveals, filters, copy buttons
};
swup.hooks.on('page:view', () => {
initPage();
});
initPage();Because initPage runs many times, each piece has to be safe to run twice. I mark elements once they’re wired up and skip them the next time.
document.querySelectorAll('[data-copy-link]:not(.is-bound)').forEach((btn) => {
btn.classList.add('is-bound');
// add the listener
});2. Forms Look Fine and Don’t Work
This one took the longest to find. My contact page uses Gravity Forms. Reached through a transition, the form looked perfect. You could fill it in and press the button. Nothing arrived.
Gravity Forms sets each form up with inline scripts that run when the page loads. Swapped in by Swup, the markup was there but that setup never ran, so the submission went in without the hidden values the plugin checks. It was filed as spam and no email was sent. There was no error anywhere.
I stopped trying to be clever. Any page with a form on it loads the old-fashioned way.
ignoreVisit: (url) =>
/(^|\/)contact\/?(\?|#|$)/.test(url)ignoreVisit tells Swup to leave a link alone and let the browser follow it. You lose the fade on that one page. You get a form that sends email, which seems like the better half of the trade.
3. Feeds and Files Aren’t Pages
Clicking the RSS link broke the site. Swup fetched /feed/, found no main element in the XML, and gave up halfway through the animation. The same goes for a link to a PDF or an image. They need ignoring too.
ignoreVisit: (url) =>
url.includes('/wp-admin') ||
url.includes('/wp-login') ||
url.includes('/wp-json') ||
/(^|\/)feed(\/|$|\?)/.test(url) ||
/\.(xml|pdf|zip|jpe?g|png|gif|webp|svg|mp4)(\?|#|$)/i.test(url)The admin links are in that list for the same reason. If you’re logged in, the admin bar is full of links that should never be swapped into your front end.
4. Comment Replies
WordPress moves the comment form under the comment you’re replying to. Its script, comment-reply, handles the Reply links itself, and it’s only loaded on single posts. Two things went wrong. Swup tried to treat the Reply link as a page visit, and a visitor who arrived at a post through a transition never got the script at all.
So the Reply links are ignored, and the script is loaded on every page.
ignoreVisit: (url, { el } = {}) =>
url.includes('replytocom=') ||
!!(el && el.closest('.comment-reply-link, #cancel-comment-reply-link'))add_action( 'wp_enqueue_scripts', function () {
if ( get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
} );5. Anchors and Scroll Position
After a swap the browser stays where it was scrolled, which is wrong for a new page and wrong again for a link that ends in #section. I put the visitor at the anchor if there is one, and at the top otherwise.
swup.hooks.on('page:view', () => {
const target = location.hash && document.querySelector(location.hash);
if (target) {
target.scrollIntoView();
} else {
window.scrollTo(0, 0);
}
});Is It Worth It?
On a content site, yes, if you’re willing to test every kind of link you have. The transitions make the site feel quicker than it measures, and the pages are still ordinary server-rendered WordPress underneath. Turn JavaScript off and everything works.
My rule now is simple. A page transition is decoration, so the moment it gets between a visitor and something that has to work, like a form, that page goes on the ignore list.
Leave a Reply