Skip to content
This repository has been archived by the owner on Jan 9, 2023. It is now read-only.

feat: More advanced YouTube pre-load decisions based on device #309

Merged
merged 10 commits into from
Dec 2, 2021
37 changes: 20 additions & 17 deletions src/YoutubeAtom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,9 @@ export const YoutubeAtom = ({
const [hasUserLaunchedPlay, setHasUserLaunchedPlay] = useState<boolean>(
false,
);
const [hasUserHovered, setHasUserHovered] = useState<boolean>(false);
const [interactionStarted, setInteractionStarted] = useState<boolean>(
false,
);
const player = useRef<YoutubePlayerType>();

const hasOverlay = overrideImage || posterImage;
Expand All @@ -191,21 +193,21 @@ export const YoutubeAtom = ({
*
*/
const showPlaceholder = !iframeSrc && (!hasOverlay || hasUserLaunchedPlay);
/**
* Load the you tube iframe if:
*
* - We have a source string defined (i.e. We have consent)
*
* and
*
* - One of these 3 things are true
* - We don't have an overlay - so we have to load the video straight away
* - The user has clicked on the overlay, so load the video iframe!
* - The user has moved their mouse over the overlay so lets pre load
* the content
*/
const loadIframe =
iframeSrc && (!hasOverlay || hasUserHovered || hasUserLaunchedPlay);

let loadIframe: boolean;
if (!iframeSrc) {
// Never try to load the iframe if we don't have a source value for it
loadIframe = false;
} else if (!hasOverlay) {
// Always load the iframe if there is no overlay
loadIframe = true;
} else if (hasUserLaunchedPlay) {
// The overlay has been clicked so we should load the iframe
loadIframe = true;
} else {
// Load early when either the mouse over or touch start event is fired
loadIframe = interactionStarted;
}

useEffect(() => {
/**
Expand Down Expand Up @@ -393,7 +395,8 @@ export const YoutubeAtom = ({
player.current.playVideo();
}
}}
onMouseEnter={() => setHasUserHovered(true)}
onMouseEnter={() => setInteractionStarted(true)}
onTouchStart={() => setInteractionStarted(true)}
css={[
overlayStyles,
hasUserLaunchedPlay ? hideOverlayStyling : '',
Expand Down