Skip to content

Commit

Permalink
Add image prefetching for lightbox images
Browse files Browse the repository at this point in the history
  • Loading branch information
Takshil-Kunadia committed Apr 25, 2024
1 parent 9cc96a7 commit 48be441
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/block-library/src/image/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,9 @@ function block_core_image_render_lightbox( $block_content, $block ) {
$p->set_attribute( 'data-wp-init', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on--load', 'callbacks.setButtonStyles' );
$p->set_attribute( 'data-wp-on-window--resize', 'callbacks.setButtonStyles' );
// Set an event to prefetch the image on pointerenter and pointerdown(mobile).
$p->set_attribute( 'data-wp-on--pointerenter', 'actions.prefetchImage' );
$p->set_attribute( 'data-wp-on--pointerdown', 'actions.prefetchImage' );
// 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
36 changes: 36 additions & 0 deletions packages/block-library/src/image/view.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,27 @@ let imageRef;
*/
let buttonRef;

/**
* Checks if the given url is a valid.
*
* @param {string} url The url to check.
*/
const isValidLink = ( url ) => {
try {
const imageUrl = new URL( url );
if (
imageUrl.origin !== window.location.origin &&
! imageUrl.pathname.startsWith( '/wp-admin' ) &&
! imageUrl.pathname.startsWith( '/wp-login.php' )
) {
return false;
}
return true;
} catch {
return false;
}
};

const { state, actions, callbacks } = store(
'core/image',
{
Expand Down Expand Up @@ -171,6 +192,21 @@ const { state, actions, callbacks } = store(
}
}
},
prefetchImage() {
const ctx = getContext();
if ( ! isValidLink( ctx.uploadedSrc ) ) {
return;
}

// Creates a link element to prefetch the image.
const imageLink = document.createElement( 'link' );
imageLink.rel = 'prefetch';
imageLink.as = 'image';
imageLink.href = ctx.uploadedSrc;

// Appends the link element to the head of the document to start the prefetch.
document.head.appendChild( imageLink );
},
},
callbacks: {
setOverlayStyles() {
Expand Down

0 comments on commit 48be441

Please sign in to comment.