Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 531
Phillip Boateng Avatar asked Jul 12 '16 10:07

Phillip Boateng


1 Answers

An updated version of @naoise-golden 's answer

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,
};
like image 87
spodell Avatar answered Oct 25 '22 04:10

spodell