Skip to content

Add Image Prefetching for Click to expand Images #61107

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
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
6 changes: 6 additions & 0 deletions packages/block-library/src/image/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ export const ALLOWED_MEDIA_TYPES = [ 'image' ];
export const MEDIA_ID_NO_FEATURED_IMAGE_SET = 0;
export const SIZED_LAYOUTS = [ 'flex', 'grid' ];
export const DEFAULT_MEDIA_SIZE_SLUG = 'full';

/**
* Delay in milliseconds before preloading an image after hovering.
* This prevents unnecessary preloading during quick scrolling or mouse movements.
*/
export const IMAGE_PRELOAD_DELAY = 200;
19 changes: 18 additions & 1 deletion packages/block-library/src/image/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,14 @@ function block_core_image_render_lightbox( $block_content, $block ) {
$img_styles = $p->get_attribute( 'style' );
$img_width = 'none';
$img_height = 'none';
$img_sizes = '100vw';
$aria_label = __( 'Enlarge' );
$dialog_aria_label = __( 'Enlarged image' );

if ( isset( $block['attrs']['id'] ) ) {
$img_uploaded_src = wp_get_attachment_url( $block['attrs']['id'] );
$img_metadata = wp_get_attachment_metadata( $block['attrs']['id'] );
$img_srcset = wp_get_attachment_image_srcset( $block['attrs']['id'] );
$img_width = $img_metadata['width'] ?? 'none';
$img_height = $img_metadata['height'] ?? 'none';
}
Expand All @@ -179,6 +181,8 @@ function block_core_image_render_lightbox( $block_content, $block ) {
'metadata' => array(
$unique_image_id => array(
'uploadedSrc' => $img_uploaded_src,
'lightboxSrcset' => $img_srcset,
'lightboxSizes' => $img_sizes,
'figureClassNames' => $figure_class_names,
'figureStyles' => $figure_styles,
'imgClassNames' => $img_class_names,
Expand Down Expand Up @@ -211,6 +215,12 @@ function block_core_image_render_lightbox( $block_content, $block ) {
$p->set_attribute( 'data-wp-init', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-async--load', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-async-window--resize', 'callbacks.setButtonStyles' );
// Set an event to preload the image on pointerenter and pointerdown(mobile).
// Pointerleave is used to cancel the preload if the user hovers away from the image
// before the predefined delay.
$p->set_attribute( 'data-wp-on--pointerenter', 'actions.preloadImageWithDelay' );
$p->set_attribute( 'data-wp-on--pointerdown', 'actions.preloadImage' );
$p->set_attribute( 'data-wp-on--pointerleave', 'actions.cancelPrefetch' );
// Sets an event callback on the `img` because the `figure` element can also
// contain a caption, and we don't want to trigger the lightbox when the
// caption is clicked.
Expand Down Expand Up @@ -302,7 +312,14 @@ class="wp-lightbox-overlay zoom"
</div>
<div class="lightbox-image-container">
<figure data-wp-bind--class="state.currentImage.figureClassNames" data-wp-bind--style="state.figureStyles">
<img data-wp-bind--alt="state.currentImage.alt" data-wp-bind--class="state.currentImage.imgClassNames" data-wp-bind--style="state.imgStyles" data-wp-bind--src="state.enlargedSrc">
<img
data-wp-bind--alt="state.currentImage.alt"
data-wp-bind--class="state.currentImage.imgClassNames"
data-wp-bind--style="state.imgStyles"
data-wp-bind--src="state.enlargedSrc"
data-wp-bind--srcset="state.enlargedSrcset"
data-wp-bind--sizes="state.enlargedSizes"
>
</figure>
</div>
<div class="scrim" style="background-color: $background_color" aria-hidden="true"></div>
Expand Down
107 changes: 103 additions & 4 deletions packages/block-library/src/image/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ import {
getContext,
getElement,
withSyncEvent,
withScope,
} from '@wordpress/interactivity';

/**
* Internal dependencies
*/
import { IMAGE_PRELOAD_DELAY } from './constants';

/**
* Tracks whether user is touching screen; used to differentiate behavior for
* touch and mouse input.
Expand All @@ -24,11 +30,46 @@ let isTouching = false;
*/
let lastTouchTime = 0;

/**
* Returns the appropriate src URL for an image.
*
* @param {string} uploadedSrc - Full size image src.
* @return {string} The source URL.
*/
function getImageSrc( { uploadedSrc } ) {
return (
uploadedSrc ||
'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
);
}

/**
* Returns the appropriate srcset for an image.
*
* @param {string} lightboxSrcset - Image srcset.
* @return {string} The srcset value.
*/
function getImageSrcset( { lightboxSrcset } ) {
return lightboxSrcset || '';
}

/**
* Returns the appropriate sizes attribute for an image.
*
* @param {string} lightboxSizes - Image responsive sizes attribute.
* @return {string} The sizes value, defaulting to 100vw.
*/
function getImageSizes( { lightboxSizes } ) {
return lightboxSizes || '100vw';
}

const { state, actions, callbacks } = store(
'core/image',
{
state: {
currentImageId: null,
preloadTimers: new Map(),
preloadedImageIds: new Set(),
get currentImage() {
return state.metadata[ state.currentImageId ];
},
Expand All @@ -42,10 +83,13 @@ const { state, actions, callbacks } = store(
return state.overlayOpened ? 'true' : null;
},
get enlargedSrc() {
return (
state.currentImage.uploadedSrc ||
'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
);
return getImageSrc( state.currentImage );
},
get enlargedSrcset() {
return getImageSrcset( state.currentImage );
},
get enlargedSizes() {
return getImageSizes( state.currentImage );
},
get figureStyles() {
return (
Expand Down Expand Up @@ -187,6 +231,61 @@ const { state, actions, callbacks } = store(
}
}
},
preloadImage() {
const { imageId } = getContext();

// Bails if it has already been preloaded. This could help
// prevent unnecessary preloading of the same image multiple times,
// leading to duplicate link elements in the document head.
if ( state.preloadedImageIds.has( imageId ) ) {
return;
}

// Link element to preload the image.
const imageMetadata = state.metadata[ imageId ];
const imageLink = document.createElement( 'link' );
imageLink.rel = 'preload';
imageLink.as = 'image';
imageLink.href = getImageSrc( imageMetadata );

// Apply srcset if available for responsive preloading
const srcset = getImageSrcset( imageMetadata );
if ( srcset ) {
imageLink.setAttribute( 'imagesrcset', srcset );
imageLink.setAttribute(
'imagesizes',
getImageSizes( imageMetadata )
);
}

document.head.appendChild( imageLink );
state.preloadedImageIds.add( imageId );
},
preloadImageWithDelay() {
const { imageId } = getContext();

// Cancels any previous preload timer for the same image.
if ( state.preloadTimers.has( imageId ) ) {
clearTimeout( state.preloadTimers.get( imageId ) );
}

// Set a new timer to preload the image after a short delay.
const timerId = setTimeout(
withScope( () => {
actions.preloadImage();
state.preloadTimers.delete( imageId );
} ),
IMAGE_PRELOAD_DELAY
);
state.preloadTimers.set( imageId, timerId );
},
cancelPrefetch() {
const { imageId } = getContext();
if ( state.preloadTimers.has( imageId ) ) {
clearTimeout( state.preloadTimers.get( imageId ) );
state.preloadTimers.delete( imageId );
}
},
},
callbacks: {
setOverlayStyles() {
Expand Down
Loading