LoginSignup
1
0

[HTML レイジーローディング] 複数の画像表示コツ

Posted at

本記事ではどのように複数な画像を適当に表示するのをご共有させていただきます

前提

・画像を1000枚表示
picsu photosでランダムな画像を取得

コード

function App() {
  const images = [];
  for (let i = 0; i < 1000; i++) {
    images.push(i);
  }
  return (
    <div className="App">
      {images.map((i) => {
        return (
          <div>
            <img src={`https://picsum.photos/500/500?random=${i}`} />
          </div>
        );
      })}
    </div>
  );
}
export default App;
/* index.css */
img {
  height: 500px;
  width: 500px;
}

レイジーローディングを導入しない

上記のコードの検査
ScreenRecording2024-05-19at15.55.34-ezgif.com-video-to-gif-converter.gif

現象

ページをレフレッシュすると画面サイズで2枚だけ表示できまが、

  • 画面を全部取得 (1回にAPIを1000件ほ叩く)
  • パフォーマス面では悪い

レイジーローディングを導入

対策

imgタグに「loading="lazy"」というプロパティを入れます

// 修正前: <img src={`https://picsum.photos/500/500?random=${i}`} />
// 修正後
 <img loading="lazy" src={`https://picsum.photos/500/500?random=${i}`} />
 

結果

  • 画像を全部取得せずにスクロールする時は該当する画像を取得
  • 1回にあたり5枚取得
    → 小さい変更ですがパフォーマンスがすごく改善できますね

 ScreenRecording2024-05-19at15.56.28-ezgif.com-video-to-gif-converter.gif

その他

DevToolsが開き方

「右マウス」→「inspect」→「network」タブ→絞り込みに「img」を選ぶ
「network」みつかない場合は[>>]をクリックしてください
Screenshot 2024-05-19 at 16.12.08.png

参考

最後までご覧くださいましてありがとうございました。
役に立つを感じしたらハートやコメントやを残ってください:bow:

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0