I have created a Section component which will take in an image as a property and its children as content to be displayed within the section, so the component would look as follows…
<Section image={'path/to/image'}>
//content
</Section>
The component will take the image property and set it as a url for background-image style…
let sectionStyle = {
backgroundImage: `url(${this.props.image})`
}
which will then be processed in the return element…
return (
<section
style={this.props.image ? sectionStyle : null}>
<div>
{this.props.children}
</div>
</section>
)
My question is, is it possible to Lazyload the background image whilst also not compromising the contents availability for SEO? in other words i want to avoid LazyLoading the entire Section, but somehow LazyLoad just the image associated with the Section.
4
Answers
I created a library for lazy-loading images. It’s main feature is to provide dynamic resizing of images, but it can also solve your problem. I recently PR’d in some changes for background image lazy loading.
https://github.com/peterlazzarino/react-adaptive-image
Here’s an example you could use for lazy background image loading that will resolve images from imgur. In my production app my image resolver points at an image server, but this is totally customize-able. You will just need to style the .header-image class to have a height and width.
Here is a simple component to lazy load images:
You would call it with
<LazyImage src='path/to/hd.jpg' placeholder='path/to/placeholder.jpg' />
An updated version of @naoise-golden ‘s answer
In order to defer loading
background-image
, you will need to create a stylesheet for the CSS properties that load any file withurl
, since you don’t want these images to delay the first contentful paint.For instance:
FirstModal.module.less
firstModalBackground.module.less
For demonstration purposes, I will use React.Component here, but, if you want to try to optimize things, you can also use React.PureComponent (I tested it and everything worked fine).
firstModal.jsx
You could even take a step further, if you have a low resolution image that loads faster, you can have a "three-step background-image loading", for instance, on componentDidMount: