WordPressでプラグインを使わずにjQuery.lazyloadをサイドバーを含めて適用する

関連記事

色々と余計な処理をしているa3 Lazy Load

当サイトでは画像の遅延読み込みにはプラグイン『a3 Lazy Load』を使っ

ていました。

https://github.com/a3rev/a3-lazy-load

速度的には全く問題ないのですが、gitのソースコードの量があまりにも多すぎるので、気分的にa3 Lazy Loadを使わずにlazyloadを適用したくなったのでコードを書きました。

置換処理部分は以下のサイトを丸写しさせていただいています。

https://nelog.jp/lazy-load-plugin-for-jquery

functions.php

add_action('dynamic_sidebar_before', 'sidebarBefore');
add_action('dynamic_sidebar_after', 'sidebarAfter');
add_filter('the_content', 'filterLazyload', 99);
add_filter('post_thumbnail_html', 'filterLazyload');
add_filter('get_avatar', 'filterLazyload');
wp_enqueue_script('lazyload', '//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js');

function sidebarBefore() {
    ob_start();
}

function sidebarAfter() {
    $content = ob_get_clean();
    $content = filterLazyload($content);

    echo $content;
}

function filterLazyload($content) {
    //プレビューやフィードモバイルなどで遅延させない
    if (is_feed() || is_preview()) {
        return $content;
    }
    //既に適用させているところは処理しない
    if (strpos($content, 'data-original') !== false) {
        return $content;
    }

    //画像正規表現で置換
    $content = preg_replace(
        '#<img([^>]+?)src=['"]?([^'"s>]+)['"]?([^>]*)>#',
        sprintf( '<img${1}src="%s" data-original="${2}"${3} data-lazy="true" /><noscript><img${1}src="${2}"${3} /></noscript>', 'data:image/gif;base64,R0lGODlhAQABAGAAACH5BAEKAP8ALAAAAAABAAEAAAgEAP8FBAA7'),
        $content);

    return $content;
}

あらかじめダミー画像を用意してもいいのですが、ここではbase64を使ってインラインで画像を埋め込んでいます。

functions.phpをクラス化している場合はadd_actionや関数の書き方が変わります。

headタグの中にJavaScriptを記述

<script>
 $(function() {
     $('img').lazyload();
     $('aside img').lazyload();
</script>

$(‘aside img’).lazyload();はサイドバーにもlazyloadを効かせて、スクロールしないと画像が読み込まれないのを防ぎます。

テーマによってはサイドバーにaside要素が使われていないかもしれないので、その場合はセレクタの調整をする必要があります。

PageSpeed Insihtsのスコアは変化なし

ソースコードを少し減らした程度ではこんなものでしょうか。

自己満足とは言え労力に見合った結果が得られず残念です。

追記: lazyloadを使わないようにしたらPageSpeed Insightsのスコアが改善しました

wordpressでlazyload(Intersection Observer)

https://qiita.com/supertaihei02/items/16853668ba6ed838085a

上記記事を参考にheadタグの中身を以下のコードに書き換えました。

<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver" defer="defer"></script>
<script>
 document.addEventListener('DOMContentLoaded', function() {
     var lazyImages = [].slice.call(document.querySelectorAll('img[data-lazy]'));

     if ('IntersectionObserver' in window) {
         var lazyImageObserver = new IntersectionObserver(function(entries, observer) {
             entries.forEach(function(entry) {
                 if (entry.isIntersecting) {
                     var lazyImage = entry.target;
                     lazyImage.src = lazyImage.dataset.original;
                     lazyImageObserver.unobserve(lazyImage);
                 }
             });
         });

         lazyImages.forEach(function(lazyImage) {
             lazyImageObserver.observe(lazyImage);
         });
     } else {
         // Possibly fall back to a more compatible method here
     }
 });
</script>

functions.phpの以下のコードが必要なくなるので削除します。

wp_enqueue_script('lazyload', '//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js');

当然ですがjQueryプラグインを使わずに実装できるなら読み込むファイルも減って処理も高速化できますね。
最近の脱jQueryの流れは疑問でしたが、ブログを軽くするためならやってみる価値はあると思いました。

関連記事

SNSでシェアする