To postpone the loading of the background-image
, a separate stylesheet needs to be created for the CSS properties that reference any files with url
. This prevents these images from delaying the initial contentful paint.
For example:
FirstModal.module.less
This file contains the essential CSS properties that load 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, React.Component is used here. However, for optimization, React.PureComponent can also be utilized (tested and worked correctly).
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 works!</div>;
}
}
module.exports = FirstModal;
To take it further, if there is a low-resolution image that loads faster, a "three-step background-image loading" approach can be implemented, like in this example using 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),
]
});
}