On-load scripts & view-transitions in Astro
- astro
- view-transitions
- script
Tue, November 14, 2023
Edit
Since the original article was written Astro has changed its API. Now the evant is called astro:page-load instead of astro:after-swap. Here is the updated code:
document.addEventListener("astro:page-load", setDarkMode);
The original article
I have a script running on page load. It’s a simple script for the dark-theme toggle. It runs on every page load (and therefore page navigations). Now, since I added View Transitions, it only runs on first page load. It doesn’t run on page navigations anymore. If you need it to run on every page load, here is the solution:
// Runs on view transitions navigation
document.addEventListener("astro:after-swap", setDarkMode);
From the great Astro documentation.
By the way if you want to have something similar, it comes from Adam Argyle’s Dark Mode Toggle.
Also, in the future, once has() support is wide enough, I am planning to switch my theme switcher to a script-less solution. Namely, using only an input combined with the has() selector on the CSS side. Like the way I implemented it my Web-Experiments example for thehas() selector: https://web-experiment.netlify.app/experiments/has-selector/. No more JS. Pure HTML & CSS 😎🚀🔥.