image lazy load 간단 정리

이미지 / 비디오 Lazy Load에 대해 알아보았다.

아래는 일반적인 img tag에 onload를 실행하여 loading이 끝났을 시 브라우저에 표시 하는 방식이다.

componentDidMount() {
  const img = new Image();
  img.src = Newman;

  img.onload = () => { // when it finishing loading, update the component state
    this.setState({ imageIsReady: true })
  }
}

render() {
  if (!imageIsReady) {
    return <div>Loading image...</div>
  } else {
    return <img src={Newman} />
  }
}

stackoverflow

그리고 아래는 백그라운드를 lazy load할때 표현법이다.

class LazyBackground 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 (
      <div
        {...this.props}
        style={{
          backgroundImage: `url(${this.state.src || this.props.placeholder})`,
        }}
      />
    )
  }
}

stackoverflow

그리고 react npm package로 react-lazy-image-component를 사용 하면 lazy load를 할 수 있다. video도 이 페키지로 사용 가능하다.

마지막으로 구글에서 설명한 lazy loading google-lazy-loading-resources


Written by@Chaehoon Lim
운동 코딩 맥주

GitHubTwitter