Pre-loading background images during Server Side Rendering
Rachna Chavan
Continuous Learner | Next.js | React.js | Javascript | Web Vitals | Accessibility
Performance optimisation is one of the key aspects to improve website conversions and gain user traffic.
While running a Google Lighthouse Performance report of a Landing page of the website I was working on; I found that the LCP score was bad. The Lighthouse report provides you the exact cause of the issue. It does the responsible DOM element highlighting, which is just awesome ?? .
From the report I observed that, it was the "hero image" that was taking long to load. I started studying about what is LCP (great resource: https://web.dev/articles/lcp) and how to tackle such issues.
My problem was that, I needed to pre-load the hero image; but:
The Solution I applied:
领英推荐
To Pre-load background images which are Client device specific:
{/* Pre-loading images */}
<link type="image/webp" rel="preload" as="image" href={urlForMobileImage} media="(max-width: 991px)" />
<link type="image/webp" rel="preload" as="image" href={urlForDesktopImage} media="(max-width: 1399px)" />
<link type="image/webp" rel="preload" as="image" href={urlForHighResolutionImage} media="(min-width: 1400px)" />
// Iv used 'useMediaQuery' from 'react-responsive' to find the user // device, on component mount.
const backgroundImage = isLargerDevice ? urlForHighResolutionImage
: isDesktopDevice
? urlForDesktopImage
: urlForMobileImage : urlForMobileImage
// Hero element
<div className="hero-image" style={{backgroundImage: `url(backgroundImage)})`/>
This was my approach, there could be many others too: like imageSrcSet, sizes, etc which one can take.
Do let me know if you too have come across, or solved similar issues, thanks for reading.