- Notifications
You must be signed in to change notification settings - Fork2
swup/astro
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Make your site feel like a snappy single-page app — without any of the complexity.
Enable smooth page transitions, smart preloading and more with thisAstro integration forswup.
Swup is a versatile and extensiblepage transition library for multi-page apps.It manages the complete page load lifecycle and smoothly animates between the current and next page.In addition, it offers many other quality-of-life improvements likecaching,smart preloading,nativebrowser history and enhancedaccessibility.
Learn more about swup in the official docs.
First, install the@swup/astro
package using your package manager.
npm install @swup/astro
Then, apply the integration to yourastro.config.*
file using theintegrations
property:
import{defineConfig}from'astro/config';importswupfrom'@swup/astro';exportdefaultdefineConfig({integrations:[swup()]});
Once the integration is installed, swup will handle and animate page visits.The necessary script is automatically added on every page of your website. Try navigating betweendifferent pages via links — you should no longer see browser refreshes and find page requestspassing through swup under the Network tab in your browser dev tools.
The next step: fine-tune your setup by reading up on availableconfiguration flags.
If you're using semantic markup and your main content area is wrapped in amain
tag, swup willwork without modifications to your site. Should you wish to replace other content containers insteadof or in addition to that, edit thecontainers options.
This integration enables swup's 'fade' theme for animated page transitions out of the box.
If you want to write your own animation styles, disable thetheme option. You thenneed to add an animation class to your animated elements and write the animation styles in CSS.See below for an example fade animation.Refer to the swup docs for a fullexample setup.
exportdefaultdefineConfig({integrations:[swup({theme:false})]});
<mainclass="transition-fade"><h1>Welcome</h1></main>
html.is-changing .transition-fade {transition:0.4s;opacity:1;}html.is-animating .transition-fade {opacity:0;}
If you don't need animated page transitions and just want to use swup for its preloading and cachingfeatures, that's fine too! In that case, disable thetheme option and pass in abooleanfalse
for theanimationClass option as well.
exportdefaultdefineConfig({integrations:[swup({theme:false,animationClass:false})]});
The integration has its own options for enabling and fine-tuning swup features. Change these in theastro.config.*
file which is where your project’s integration settings live. These are the defaults:
import{defineConfig}from'astro/config';importswupfrom'@swup/astro';exportdefaultdefineConfig({integrations:[swup({theme:'fade',animationClass:'transition-',containers:['main'],cache:true,preload:true,accessibility:true,forms:false,morph:false,parallel:false,progress:false,routes:false,smoothScrolling:true,updateBodyClass:false,updateHead:true,reloadScripts:true,debug:false,loadOnIdle:true,globalInstance:false,})]});
Use one of swup's predefined themes to get started with animated page transitions.
Set tofalse
if you want to define your own animation styles.
{theme:'fade'|'slide'|'overlay'|false}
Pass in an array with the theme name and an object to override specific theme options:
{theme:['overlay',{direction:'to-right'}]}
If you're not using one of the provided themes, you will need this class for defining your ownanimation styles.
The class prefix for detecting animation timing. Swup will wait for all CSS transitions andkeyframe animations to finish on these elements before swapping in the content of the new page.The default option will select all elements with class names beginning intransition-
.
{animationClass:'transition-'}
The content containers to be replaced on page visits. Usually the<main>
element with the contentof the page, but can include any other elements that are present across all pages.Defaults to the firstmain
tag of the page.
Note: Only elementsinside of thebody
tag are supported.
{containers:['#content','#nav']}
The built-in cache keeps previously loaded pages in memory. This improves speed but can be disabledfor highly dynamic sites that need up-to-date responses on each request.
{cache:false}
Smart preloading, enabled by default. Pass in an object to enable or disable preloading features:
{preload:{hover:true,visible:false}}
Swup will preload links when they are hovered with a mouse, touched with a finger, or focused usingthe keyboard. Enabled by default.
Preload links as they enter the viewport. Not enabled by default, but recommended for a performanceboost to static sites.
In addition to preloading links when interacting with them, you can mark links for preloadingmanually by applying adata-swup-preload
attribute on the link, or adata-swup-preload-all
on acommon parent:
<!-- preload a single link --><ahref="/about"data-swup-preload>About</a><!-- preload all links in a container --><navdata-swup-preload-all><ahref="/about">About</a><ahref="/contact">Contact</a></nav>
Enhance accessibility for screen readers by announcing page visits and focussing the newly updatedcontent after page visits.
{accessibility:true}
If you want swup to handle form submissions as well, enable this option. Note: swup handlesreasonable scenarios like search or contact forms. For complex requirements like file uploads orcustom serialization, it is recommended to use the swup API directly.
{forms:true}
Form submissions trigger normal swup navigations: they will animate and replace the contentcontainers as on other visits. If you'd rather submit the form inline and only animate andupdate the form itself, add adata-swup-inline-form
attribute and a uniqueid
to the form:
<formid="contact-form"class="transition-form"data-swup-inline-form>
The animation classes are then only added to the form itself:
.transition-form.is-changing {transition: opacity200ms;}.transition-form.is-animating {opacity:0;}
To disable swup for specific forms, add adata-no-swup
attribute on the form element:
<formaction="/"data-no-swup>
Morph certain containers into the new page without replacing them entirely. Usesmorphdom to only update the attributes,classnames and text content of elements that have changed, instead of replacing the wholecontainer. This keeps any existing state such as event handlers and scroll positions.
The prime use cases are headers and menus on multi-language sites: you might not want to swap theseelements out with a transition on each page visit, however you'd still want to update any URLs,labels or classnames when the user switches between languages, without losing event handlers.
{morph:['#nav','#sidebar']}
Swup page transitions usually work in series: hide the current page, update the content, show thenew page. If you want to combine the leave/enter animations and keep the previous content visibleduring the animation, enable this option. Doing so will allow synchronous animations like overlays,crossfades, or slideshows.
For details on the lifecycle and styling of parallel animations, check out thereadme of swup'sParallel Plugin.
{parallel:true}
This will run all animations for all containers in parallel. If you only want to animate certaincontainers in parallel, pass an array of container selectors:
{ containers:['nav','main'] parallel:['main']}
Display a progress bar for all requests taking longer than ~300ms.
{progress:true}
The progress bar has a class name ofswup-progress-bar
you can use for styling.
.swup-progress-bar {height:4px;background-color: blue;}
Use path and route names to allow choosing between animations. Given a list of URL patterns,usespath-to-regexp to identify named routes andadds them as classnames to use for styling animations, e.g.from-route-home
orto-route-project
.
{routes:[{name:'home',path:'/:lang?'},{name:'projects',path:'/:lang/projects'},{name:'project',path:'/:lang/project/:slug'}]}
Navigating from/en/
to/en/project/some-project/
will add these classes:
<htmlclass="is-animating from-route-home to-route-project">
Enable acceleration-based smooth scrolling, animated scroll positions between page visits and foranchor jump links.
{smoothScrolling:true}
Update the body class after each page visit. Useful if you use classes on the body element forstyling site sections.
{updateBodyClass:true}
Update the contents of thehead
tag after each page visit. Useful if you have differingstylesheets per section of your site.
{updateHead:true}
Re-run anyscript
tags inside thehead
andbody
on every page view. Helpful as a last resortfor sites with limited control over the included scripts. Beware: Running scripts without destroyingprevious ones can cause memory leaks and potentially break your page.
{reloadScripts:true}
Add debug output by swup and its plugins to the browser console. Useful during development.
{debug:true}
Swup is a progressive enhancement and doesn't need to be loaded immediately. By default, thisintegration will only initialize swup when the browser is idle, after the document has finishedloading. This improves first-load performance of the site. If for whatever reason you need toinitialize swup immediately on load, set this option tofalse
.
{loadOnIdle:true}
Store the initialized swup instance inwindow.swup
. Useful if you need to add custom hooks orplugins.
{globalInstance:true}
For more advanced usage like registering hook handlers or installing custom plugins, you need accessto the swup instance itself. Enable theglobalInstance
option to have the swup instance availableatwindow.swup
. You can then use swup's API directly.
exportdefaultdefineConfig({integrations:[swup({globalInstance:true})]});
<script>window.swup.use(newMyCustomSwupPlugin())window.swup.hooks.on('page:view',()=>{})</script>
Note: The global instance might not be available immediately since swup is loaded when thebrowser is idle. In that case, you can listen for theenable
event on the document.
<script>constsetup=()=>{window.swup.use(newMyCustomSwupPlugin())window.swup.hooks.on('page:view',()=>{})}if(window.swup){setup()}else{document.addEventListener('swup:enable',setup)}</script>
If you need more granularity during the initilization process itself, consider followingthe manual swup setup instead. As a minimalrequirement, you should install the head plugin and the scripts plugin so that client-sidecomponents are hydrated correctly.
<!-- Layout.astro or another global file --><script>importSwupfrom'swup';importSwupHeadPluginfrom'@swup/head-plugin';importSwupScriptsPluginfrom'@swup/scripts-plugin';constswup=newSwup({plugins:[newSwupHeadPlugin(),newSwupScriptsPlugin()]});</script>
Having trouble implementing swup? Check out theofficial docs, look atpast issues or create anew discussion.
You can also check theAstro Integration Documentation for more on integrations.
This package is maintained by the swup core team. You're welcome to submit an issue or PR.
SeeChangelog for a history of changes to this integration.
About
Astro integration for swup 🚀