Skip to content
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

PoC for preloading responsive images for blocks #2322

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
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
30 changes: 30 additions & 0 deletions assets/src/blocks/CarouselHeader/SlideBackground.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,41 @@
function parseWidths(srcset) {
const entries = srcset.split(',').map(entry => entry.trim());
const widths = entries.map(entry => {
const width = entry.split(' ')[1];
return width.replace('w', 'px');
});
return widths;
}

function createSizesAttribute(widths) {
return widths.map(width => {
return `(max-width: ${parseInt(width)}px) ${width}`;
}).join(', ');
}

export const SlideBackground = ({slide, decoding}) => {
const {image_url, image_srcset, focal_points, image_alt} = slide;
const image_widths = parseWidths(image_srcset);
const image_sizes = createSizesAttribute(image_widths);

// Preload the images
if (image_srcset && image_sizes) {
const preloadLink = document.createElement('link');
preloadLink.rel = 'preload';
preloadLink.as = 'image';
preloadLink.href = image_url;
preloadLink.imagesrcset = image_srcset;
preloadLink.imagesizes = image_sizes.concat(', 100vw');
document.head.appendChild(preloadLink);
}

return (
<div className="background-holder">
<img
src={image_url}
style={{objectPosition: `${(focal_points?.x || .5) * 100}% ${(focal_points?.y || .5) * 100}%`}}
srcSet={image_srcset}
sizes={image_sizes}
alt={image_alt}
{...decoding ? {decoding: 'async'} : {}}
/>
Expand Down