是否可以使用反应延迟加载延迟加载背景图像

Is it possible to lazy load background images with react-lazyload

本文关键字:延迟加载 背景 图像 可以使 是否      更新时间:2023-09-26
我创建了一个 Section 组件,该组件将图像作为

属性,将其子级作为要在该部分中显示的内容,因此该组件如下所示...

<Section image={'path/to/image'}>
 //content
</Section>

该组件将采用 image 属性并将其设置为背景图像样式的 url...

let sectionStyle = {
  backgroundImage: `url(${this.props.image})`
}

然后将在返回元素中进行处理...

return (
  <section
    style={this.props.image ? sectionStyle : null}>
    <div>
      {this.props.children}
    </div>
  </section>
)

我的问题是,是否可以延迟加载背景图像,同时不影响 SEO 的内容可用性? 换句话说,我想避免 LazyLoading 整个部分,但不知何故 LazyLoad 只是与该部分关联的图像。

@naoise-gold的答案的更新版本

import PropTypes from 'prop-types';
import React from 'react';
export default class LazyImage extends React.Component {
  constructor (props) {
    super(props);
    this.state = {
      src: null,
    };
  }
  componentDidMount () {
    const { src } = this.props;
    console.log('LazyImage componentDidMount props:', this.props);
    const imageLoader = new Image();
    imageLoader.src = src;
    imageLoader.onload = () => {
      console.log('LazyImage loaded src:', src);
      this.setState({ src });
    };
  }
  render () {
    const { placeholder, className, height, width, alt } = this.props;
    const { src } = this.state;
    return (
      <img src={src || placeholder} className={className} height={height} width={width} alt={alt} />
    );
  }
}
LazyImage.propTypes = {
  src: PropTypes.string,
  placeholder: PropTypes.string,
  className: PropTypes.string,
  height: PropTypes.number,
  width: PropTypes.number,
  alt: PropTypes.string,
};

为了延迟加载background-image,您需要为加载任何url文件的 CSS 属性创建一个样式表,因为您不希望这些图像延迟第一次内容绘制。例如:

FirstModal.module.less

此文件具有将首先加载的重要 CSS 属性...

.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

此文件将在关键 CSS 之后加载...

.styles {
    &-container {
        background: url('../../images/code/code.jpg') no-repeat center center fixed;
        background-size: cover;
    }
}

出于演示目的,我将在这里使用 React.Component,但是,如果你想尝试优化事物,你也可以使用 React.PureComponent(我测试了它,一切正常)。

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;

您甚至可以更进一步,如果您有一个加载速度更快的低分辨率图像,则可以在组件DidMount上进行"三步背景图像加载":

    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),
            ]
        });
    }

下面是延迟加载图像的简单组件:

class LazyImage extends React.Component {
  state = { src: null };
  componentDidMount() {
    const { src } = this.props;
    const imageLoader = new Image();
    imageLoader.src = src;
    imageLoader.onload = () => {
      this.setState({ src });
    };
  }
  render() {
    return <img src={this.state.src || this.props.placeholder} />;
  }
}

你会用<LazyImage src='path/to/hd.jpg' placeholder='path/to/placeholder.jpg' />来称呼它

我创建了一个用于延迟加载图像的库。它的主要功能是提供图像的动态调整大小,但它也可以解决您的问题。我最近对背景图像延迟加载进行了一些更改。

https://github.com/peterlazzarino/react-adaptive-image

下面是一个可用于延迟背景图像加载的示例,该示例将解析来自 imgur 的图像。在我的生产应用程序中,我的图像解析器指向图像服务器,但这完全是可自定义的。您只需要将 .header-image 类的样式设置为具有高度和宽度。

import React from 'react';
import ReactDOM from 'react-dom';
import { initImages } from 'react-adaptive-image';
import AdaptiveImage from 'react-adaptive-image';
initImages({
    imageResolver: function(image){
        return `https://i.imgur.com/${image.fileName}`
    }
})
class App extends React.Component {
    render() {
      return (
        <AdaptiveImage backgroundImage className="header-image" fileName={'U6zWkcZ.png'} />
      );
    }
  }
ReactDOM.render(<App />, document.getElementById('react-root'));