View conversion in Astro: a powerful tool for smooth page switching
This article is excerpted from SitePoint Premium's book "Unleashing the Power of Astro", which introduces the view conversion function in Astro.
The View Transformation API provides a convenient way to simultaneously update DOM content in a single operation and generate animation conversion effects between individual DOM states. Implementing this on the web in the past was very difficult, but with this new API, the transformation became fairly easy. Research shows that using the view conversion API can speed up the perceived performance of a website.
Astro natively supports view conversion and has a built-in fallback mechanism to support browsers that do not currently support this API.
This native solution supports built-in animation, front and back navigation animations, and automatic accessibility support (via prefers-reduced-motion
), and many other features.
One of the best ways to demo view conversion is to use a video element that will keep its state between page conversions. (Note that we can also keep state between components using the client:*
directive.) The video below shows an example.
Suppose we have a <video></video>
component that contains the following:
<code>--- // src/components/Video const src = 'https://res.cloudinary.com/tamas-demo/video/upload/f_auto,q_auto/imagecon/ship.mp4'; const { autoplay = false, controls = true, loop = false } = Astro.props; --- <video transition:persist=""></video></code>
In the above code, we get a video from Cloudinary. In addition, we allow videos to automatically play and loop after playback, and provide users with control buttons. These settings are determined by the properties sent to this video component, and if these properties are not provided, the default values are used. These variables are then added to the HTML<video></video>
element.
Please note the transition:persist
command. With this command, we will keep the video player between transitions: when navigating to the next page, the video will continue to play, while the rest of the page will display updated content. We can use this component on the index.astro
and about.astro
pages:
<code>// src/pages/index.astro --- import Video from '../components/Video.astro'; --- <video></video></code>
Finally, we need to enable page conversion, which we can enable for each page or globally for the entire project. Assuming we have some sort of layout file, we can easily enable it by importing astro:transitions
from: ViewTransitions
<code>// src/layouts/Layout.astro --- import { ViewTransitions } from 'astro:transitions'; --- <title>My site!</title> <viewtransitions></viewtransitions> <slot></slot> </code>
The above is the detailed content of View Transitions in Astro. For more information, please follow other related articles on the PHP Chinese website!