Skip to content

Commit 48be441

Browse files
Add image prefetching for lightbox images
1 parent 9cc96a7 commit 48be441

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

packages/block-library/src/image/index.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,9 @@ function block_core_image_render_lightbox( $block_content, $block ) {
190190
$p->set_attribute( 'data-wp-init', 'callbacks.setButtonStyles' );
191191
$p->set_attribute( 'data-wp-on--load', 'callbacks.setButtonStyles' );
192192
$p->set_attribute( 'data-wp-on-window--resize', 'callbacks.setButtonStyles' );
193+
// Set an event to prefetch the image on pointerenter and pointerdown(mobile).
194+
$p->set_attribute( 'data-wp-on--pointerenter', 'actions.prefetchImage' );
195+
$p->set_attribute( 'data-wp-on--pointerdown', 'actions.prefetchImage' );
193196
// Sets an event callback on the `img` because the `figure` element can also
194197
// contain a caption, and we don't want to trigger the lightbox when the
195198
// caption is clicked.

packages/block-library/src/image/view.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,27 @@ let imageRef;
3333
*/
3434
let buttonRef;
3535

36+
/**
37+
* Checks if the given url is a valid.
38+
*
39+
* @param {string} url The url to check.
40+
*/
41+
const isValidLink = ( url ) => {
42+
try {
43+
const imageUrl = new URL( url );
44+
if (
45+
imageUrl.origin !== window.location.origin &&
46+
! imageUrl.pathname.startsWith( '/wp-admin' ) &&
47+
! imageUrl.pathname.startsWith( '/wp-login.php' )
48+
) {
49+
return false;
50+
}
51+
return true;
52+
} catch {
53+
return false;
54+
}
55+
};
56+
3657
const { state, actions, callbacks } = store(
3758
'core/image',
3859
{
@@ -171,6 +192,21 @@ const { state, actions, callbacks } = store(
171192
}
172193
}
173194
},
195+
prefetchImage() {
196+
const ctx = getContext();
197+
if ( ! isValidLink( ctx.uploadedSrc ) ) {
198+
return;
199+
}
200+
201+
// Creates a link element to prefetch the image.
202+
const imageLink = document.createElement( 'link' );
203+
imageLink.rel = 'prefetch';
204+
imageLink.as = 'image';
205+
imageLink.href = ctx.uploadedSrc;
206+
207+
// Appends the link element to the head of the document to start the prefetch.
208+
document.head.appendChild( imageLink );
209+
},
174210
},
175211
callbacks: {
176212
setOverlayStyles() {

0 commit comments

Comments
 (0)