1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

loading属性を使って画像の遅延読み込みを実装してみる

Posted at

はじめに

loading属性を使用する事で画像やiframe要素を遅延読み込みする事ができます。
初回の読み込み時に必要のないものは遅延読み込みにすることにより、初回のページ読み込みのパフォーマンスを向上する事ができます。

loading属性とは?

loading属性で指定できる値としては、eagerlazyの2つがあります。

  • loading="eager": 初回の読み込み時に対象のリソースを読み込まれます。
  • loading="lazy":画像やiframe要素などユーザのスクロールが対象の要素に近づいたらリソースが読み込まれます。

eagerとlazyを指定した要素を作ってみる

下記のようにサンプルページを作ってみます。
ページ上部からeagerを指定した要素を1つと、lazyで指定した要素が2つ作成しています。
初回ロードではeagerを指定した「Eager サンプル」要素が読み込まれ、
スクロールに合わせてlazyで指定した「Lazy サンプル」要素が読み込まれます。

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sample-page</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="blank-space">
        <h1>余白</h1>
    </div>

    <div class="eager">
        <h1>Eager サンプル</h1>
        <img src="https://via.placeholder.com/1000x400" alt="Eager Loading" loading="eager">    
    </div>

    <div class="blank-space">
        <h1>余白</h1>
    </div>

    <div>
        <h1>Lazy サンプル1</h1>
        <img src="https://via.placeholder.com/1000x600" alt="Lazy Loading" loading="lazy">
    </div>

    <div class="blank-space">
        <h1>余白</h1>
    </div>

    <div>
        <h1>Lazy サンプル2</h1>
        <img src="https://via.placeholder.com/1000x800" alt="Lazy Loading" loading="lazy">
    </div>
</body>
</html>
index.css
index.css
body {
  text-align: center;
}

.blank-space {
  height: 1200px;
  font-size: 1.3rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: lightblue;
}

検証ツールを使用して動作を確認

vscodeからサーバを起動しブラウザで確認してきます。
chromeの検証ツールからネットワークタブを選択しページを再読み込みすると、
初回の読み込み時にはeagerを指定した画像(1000x400)は読み込まれいるのが確認できます。

image.png

下にスクロールしてみると、lazyを指定した画像(1000x600、1000x800)がスクロールに合わせて読み込まれたのが確認できます。

image.png

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?