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 11 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
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
60 changes: 60 additions & 0 deletions packages/block-library/src/image/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
getContext,
getElement,
withSyncEvent,
withScope,
} from '@wordpress/interactivity';

/**
Expand All @@ -29,6 +30,8 @@ const { state, actions, callbacks } = store(
{
state: {
currentImageId: null,
preloadTimers: {},
preloadedImageIds: new Set(),
get currentImage() {
return state.metadata[ state.currentImageId ];
},
Expand All @@ -47,6 +50,12 @@ const { state, actions, callbacks } = store(
'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs='
);
},
get enlargedSrcset() {
return state.currentImage.lightboxSrcset || '';
},
get enlargedSizes() {
return state.currentImage.lightboxSizes || '100vw';
},
get figureStyles() {
return (
state.overlayOpened &&
Expand Down Expand Up @@ -187,6 +196,57 @@ const { state, actions, callbacks } = store(
}
}
},
preloadImage() {
const { imageId } = getContext();
const imageMetadata = state.metadata[ imageId ];
const uploadedSrc = imageMetadata.uploadedSrc;

// 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;
}

const imageLink = document.createElement( 'link' );
imageLink.rel = 'preload';
imageLink.as = 'image';
imageLink.href = uploadedSrc;

// Apply srcset if available for responsive preloading
const srcset = imageMetadata.lightboxSrcset;
if ( srcset ) {
imageLink.setAttribute( 'imagesrcset', srcset );
imageLink.setAttribute( 'imagesizes', '100vw' );
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't enlargedSrcset and enlargedSizes be used here?

Copy link
Contributor Author

@Takshil-Kunadia Takshil-Kunadia Jun 24, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can use the getter functions, but for that we need to temporarily set the currentImageId to use them and then reset the Id when we have preloaded the image.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for that we need to temporarily set the currentImageId to use them and then reset the Id when we have preloaded the image

I don't think it would be a good approach, as there can be more than one image preloading at the same time.

Why don't you just use imageMetadata.lightboxSizes || '100vw' instead of just '100vw' here?

Copy link
Contributor Author

@Takshil-Kunadia Takshil-Kunadia Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was how it was implemented previously. I changed it in cab1562 to use the getter fns.
Reverted this commit ↩️ along with the dynamic lightboxSizes change


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

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

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