Skip to content

Commit 8c5487f

Browse files
committed
PoC for preloading responsive images for blocks
- Testing out the functionality using the Carousel Block
1 parent 5904c3e commit 8c5487f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

assets/src/blocks/CarouselHeader/SlideBackground.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,44 @@
1+
function parseWidths(srcset) {
2+
const entries = srcset.split(',').map(entry => entry.trim());
3+
const widths = entries.map(entry => {
4+
const width = entry.split(' ')[1];
5+
return width?.replace('w', 'px');
6+
});
7+
return widths;
8+
}
9+
10+
function createSizesAttribute(widths) {
11+
return widths.map(width => {
12+
return `(max-width: ${parseInt(width)}px) ${width}`;
13+
}).join(', ');
14+
}
15+
116
export const SlideBackground = ({slide, decoding}) => {
217
const {image_url, image_srcset, focal_points, image_alt} = slide;
18+
const image_widths = parseWidths(image_srcset);
19+
const image_sizes = createSizesAttribute(image_widths);
20+
21+
// Preload the images
22+
if (image_srcset && image_sizes) {
23+
const preloadLink = document.createElement('link');
24+
preloadLink.rel = 'preload';
25+
preloadLink.as = 'image';
26+
preloadLink.href = image_url;
27+
preloadLink.setAttribute('imagesrcset', image_srcset);
28+
preloadLink.setAttribute('imagesizes', image_sizes.concat(', 100vw'));
29+
document.head.appendChild(preloadLink);
30+
}
31+
332
return (
433
<div className="background-holder">
534
<img
635
src={image_url}
736
style={{objectPosition: `${(focal_points?.x || .5) * 100}% ${(focal_points?.y || .5) * 100}%`}}
837
srcSet={image_srcset}
38+
sizes={image_sizes}
939
alt={image_alt}
40+
// eslint-disable-next-line react/no-unknown-property
41+
fetchpriority="high"
1042
{...decoding ? {decoding: 'async'} : {}}
1143
/>
1244
</div>

0 commit comments

Comments
 (0)