【Blogger】追記あり 自動で記事内の画像にloading="lazy"を付ける【JavaScript】

更新  
公開
当サイトはアフィリエイト広告を使用しています

Blogger QooQ



この記事は公開から3年以上が経過しています
アイキャッチ

追記(2022年2月27日):PageSpeed Insightsの「オフスクリーン画像の遅延読み込み」の指摘は回避することは出来ましたが、実際のパフォーマンス向上は確認出来ません。Twitterで教えてもらいました
あくまで実験的なものとご理解ください。

手動でloading="lazy"を付けるのが地味に面倒だったので作ってみました。

最初の画像にはloading="lazy"を付けないほうがいい場合もあるらしいので、最初の画像を除くタイプも作りました。PageSpeed Insights等で確認してください。

下記のような構造になっている画像(class="separator"以下のイメージタグ<img>)に適応されます。

<div class="separator" style="clear: both;">
 <a href="https:..." style="...">
  <img alt="" border="0" width="" data-original-height="" data-original-width="" src="https:..."/>
</a></div>

</body>の上あたりに設置してください。

HTMLを編集します。必ずバックアップを取ってから作業してください。

目次

すべての画像にloading="lazy"を付ける

<script>
//<![CDATA[
(() => {
  const basePoint = document.querySelector(".post-body");

  const postImages = basePoint.querySelectorAll(".separator img");

  if (postImages.length > 0) {
    postImages.forEach((element) => {
      element.setAttribute("loading", "lazy");
      //element.setAttribute("decoding", "async");
    });
  } else {
  }
})();
//]]>
</script>

最初の画像を除く

<script>
//<![CDATA[
(() => {
  const basePoint = document.querySelector(".post-body");

  const postImages = Array.from(basePoint.querySelectorAll(".separator img"));

  if (postImages.length > 0) {
    postImages.shift();
    postImages.forEach((element) => {
      element.setAttribute("loading", "lazy");
      //element.setAttribute("decoding", "async");
    });
  } else {
  }
})();
//]]>
</script>

最初の画像にdecoding="async"を付ける

<script>
//<![CDATA[
(() => {
  const basePoint = document.querySelector(".post-body");

  const postImages = Array.from(basePoint.querySelectorAll(".separator img"));

  if (postImages.length > 0) {
    postImages[0].setAttribute("decoding", "async");
    postImages.shift();
    postImages.forEach((element) => {
      element.setAttribute("loading", "lazy");
      //element.setAttribute("decoding", "async");
    });
  } else {
  }
})();
//]]>

</script>

もっとキレイな方法があるはず。。。

補足

汎用性が高そうな、.post-bodyを記事内を指定するセレクターに使いました。

const basePoint = document.querySelector(".post-body");

お使いのテンプレートによってはセレクターを変更する必要があります。

投稿とページのみに適用させる場合<b:if cond='data:view.isSingleItem'>...</b:if><b:if cond='data:view.isSingleItem and data:view.featuredImage'>...</b:if>などを使ってください。

<b:if cond='data:view.isSingleItem and data:view.featuredImage'>

コード

</b:if>


検索

お知らせ

カテゴリー

Random Picks

すたすた式

Enjoy!👍

QooQ