|
| 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 | + |
1 | 16 | export const SlideBackground = ({slide, decoding}) => { |
2 | 17 | 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.imagesrcset = image_srcset; |
| 28 | + preloadLink.imagesizes = image_sizes.concat(', 100vw'); |
| 29 | + document.head.appendChild(preloadLink); |
| 30 | + } |
| 31 | + |
3 | 32 | return ( |
4 | 33 | <div className="background-holder"> |
5 | 34 | <img |
6 | 35 | src={image_url} |
7 | 36 | style={{objectPosition: `${(focal_points?.x || .5) * 100}% ${(focal_points?.y || .5) * 100}%`}} |
8 | 37 | srcSet={image_srcset} |
| 38 | + sizes={image_sizes} |
9 | 39 | alt={image_alt} |
10 | 40 | {...decoding ? {decoding: 'async'} : {}} |
11 | 41 | /> |
|
0 commit comments