In order to defer loading background-image
, you will need to create a stylesheet for the CSS properties that load any file with url
, since you don't want those images to delay the first contentful paint.
For instance:
FirstModal.module.less
This file has the vital CSS properties that will be loaded first...
.styles {
&-container {
position: absolute;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-content: center;
justify-content: center;
align-items: center;
}
}
firstModalBackground.module.less
This file will load after the critical CSS...
.styles {
&-container {
background: url('../../images/code/code.jpg') no-repeat center center fixed;
background-size: cover;
}
}
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
const classNames = require('classnames');
const React = require('react)';
const {stylesContainer} = require('./firstModal.module.less');
class FirstModal extends React.Component {
constructor(props) {
super(props);
this.state = {
classNames: classNames([stylesContainer])
};
}
async componentDidMount() {
const backgroundImage = await import(
'./firstModalBackground.module.less'
);
this.setState({
classNames: [
classNames(this.state.classNames, [backgroundImage.stylesContainer]),
]
});
}
render() {
// console.log(this.state.classNames);
return <div className={this.state.classNames}>It werks!</div>;
}
}
module.exports = FirstModal;
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:
async componentDidMount() {
const lowResolutionBackgroundImage = await import(
'../greeting-page/firstModalLowResBackground.module.less'
);
const baseClass = this.state.classNames;
this.setState({
classNames: [
classNames(baseclass,
lowResolutionBackgroundImage.stylesContainer),
]
});
const backgroundImage = await import(
'./firstModalBackground.module.less'
);
this.setState({
classNames: [
classNames(baseClass,
backgroundImage.stylesContainer),
]
});
}