Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strong-crabs-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wethegit/react-autoplay-video": patch
---

Adds loading prop, allowing for lazy and eager loading of the video element.
24 changes: 2 additions & 22 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 20 additions & 3 deletions src/lib/components/autoplay-video.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import { classnames } from "../utils/classnames"

import styles from "./autoplay-video.module.css"

declare module "react" {
interface VideoHTMLAttributes<T> extends React.HTMLAttributes<T> {
loading?: "lazy" | "eager"
}
}

export interface AutoplayVideoProps extends React.ComponentPropsWithRef<"div"> {
/**
* Visually-hidden description of the video.
Expand Down Expand Up @@ -36,6 +42,10 @@ export interface AutoplayVideoProps extends React.ComponentPropsWithRef<"div"> {
* Video path to use as the video element's src attribute.
*/
src: string
/**
* Whether or not to add the loading attribute to the video element.
*/
Comment thread
Copilot marked this conversation as resolved.
loading?: "lazy" | "eager"
}

/**
Expand All @@ -51,9 +61,10 @@ export function AutoplayVideo({
renderReducedMotionFallback,
src,
loop = true,
loading,
...props
}: AutoplayVideoProps) {
const [srcAdded, setSrcAdded] = useState(false)
const [srcAdded, setSrcAdded] = useState(loading === "eager")
const [setInViewRef, isInView] = useInView<HTMLDivElement>(0)
const descriptionID = useId()
const videoRef = useRef<HTMLVideoElement | null>(null)
Expand All @@ -72,8 +83,13 @@ export function AutoplayVideo({

// Set a flag to load the content (video or fallback), based on its visibility.
useEffect(() => {
if (isInView) setSrcAdded(true)
}, [isInView])
if (loading === "eager") {
setSrcAdded(true)
return
}

setSrcAdded(isInView)
}, [isInView, loading])

// Ensure the video does not continue to play when off-screen.
// Play/pause the video based on the `paused` override prop.
Expand Down Expand Up @@ -109,6 +125,7 @@ export function AutoplayVideo({
aria-describedby={descriptionID}
autoPlay
className={styles["autoplay-video__media"]}
loading={loading}
loop={loop}
Comment thread
NicholasLancey marked this conversation as resolved.
muted
playsInline
Expand Down
Loading