이미지 최적화 - 렌더링 로딩처리

뱀기·2023년 7월 10일
0

Nurihaus

목록 보기
12/13
post-thumbnail

문제 분석

  • 업로드 되는 동안 이미지가 고화질인 경우 load 되는 시간이 길다.

목표

  • 이미지가 렌더되는 과정을 로딩처리를 한다.
  • UX 증진

설정

  • 로딩 컴포넌트 만들기 (알아서...!)
  • 이미지 로더 생성 (onload되는 경우 state가 바뀌면서 loading 컴포넌트가 보이다 이미지가 보이도록한다)
import { CSSProperties, useState } from 'react';
import styled from 'styled-components';

interface IProps {
  src: string;
  alt: string;
  loadingComponent: JSX.Element;
  style?: CSSProperties;
}

export default function ImageLoader({
  src,
  alt,
  loadingComponent,
  style,
}: IProps) {
  const [isLoading, setIsLoading] = useState(true);

  const handleLoad = () => {
    setIsLoading(false);
  };

  return (
    <>
      {isLoading && (
        <div
          style={style}
        >
          {loadingComponent}
        </div>
      )}
      <img
        src={src}
        alt={alt}
        onLoad={handleLoad}
        style={{...style, display: isLoading ? 'none' : 'block'}}
      />
    </>
  );
}
  • 가독성을 위해 스타일을 따로 위에 변수로 선언해서 관리하고 있다.
  • 로딩 컨테이너와 이미지가 어느정도 같은 스타일을 공유함.

결과

  • src와 alt, loadingcomponent만 넣으면 간단하게 로딩 이후 이미지가 업로드 되게 할 수 있다.

쉽게 이미지 로드 로딩을 만들어보았다.

0개의 댓글