From c0a02247ee112f2aab9a0779859717fbe9127ad1 Mon Sep 17 00:00:00 2001 From: Osong Agberndifor Date: Mon, 15 Jul 2024 10:29:10 +0100 Subject: [PATCH] PoC for preloading responsive images for blocks - Testing out the functionality using the Carousel Block --- .../blocks/CarouselHeader/SlideBackground.js | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/assets/src/blocks/CarouselHeader/SlideBackground.js b/assets/src/blocks/CarouselHeader/SlideBackground.js index a4d47a7054..5d5c0551d5 100644 --- a/assets/src/blocks/CarouselHeader/SlideBackground.js +++ b/assets/src/blocks/CarouselHeader/SlideBackground.js @@ -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 (
{image_alt}