■【ファーストビュー関連】投稿ページの最初の画像をpreloadで先読みする方法

コアウェブバイタルのLCP対策で、ブログ記事の最初の画像のみ、読み込み速度を上げるためpreloadで先読みさせ、ファーストビューの表示速度を上げる。

■function.phpの記述

<?php

//■ブログ記事の一番上の画像をpreloadで先読み込み(※header.phpに呼び出し記述あり)

//投稿記事の最初の画像をpreloadの読み込み形式に変換
function catch_preload_image($altimg_id = null) {
global $post;
$image = '';

//正規表現で記事中の一番上の画像を探す
$image_get = preg_match_all( '/<img.*?src=(["\'])(.+?)\1.+class=["\'].*wp-image-([0-9]+).*["\'].*>/i', $post->post_content, $matches );

//記事中の一番上のimgのID取得
if (isset($matches[3][0])) {
$image_id = $matches[3][0];
} else {
$image_id = '';
}

//記事中の一番上のimgのURL取得
if (isset($matches[2][0])) {
$first_img = $matches[2][0];
} else {
$first_img = '';
}

//$altimg_idの値(画像のID指定をする場合)の値があったら指定した画像の情報を取得。※特に今は使わない。
if( !$image_id && $altimg_id ){
$image_id = $altimg_id;
}

//記事中の一番上の画像のサムネイル画像情報を取得してsrcsetとsizesの値を取得
$img_srcset = wp_get_attachment_image( $image_id, 'thumbnail', false, array(
'srcset' => wp_get_attachment_image_srcset( $image_id),
'sizes' => wp_get_attachment_image_sizes( $image_id)
));

//正規表現で記事中の一番上の画像のsrcsetとsizesの値だけを抜き取り
$img_srcset = preg_match_all('/<img.*?srcset=["\'](.+?)["\'].*?sizes=["\'](.+?)["\'].*>/i', $img_srcset, $matches2);

//srcsetとsizes属性用のpreload記述を構築
if ( isset($matches2[1][0]) || isset($matches2[2][0])) {
$image1 = '<link rel="preload" as="image" href="' . $first_img . '" imagesrcset="' . $matches2[1][0] . '" imagesizes="' . $matches2[2][0] . '">';
} else {
$image1 = '';
}

//このままのpreload形式だとsizes属性がデバイスピクセル比3倍→2倍対策ができていないので下記の記述でsizes属性を変換。※必要ない時は記述ごと消して、上記のimage1をimageに変えてつなげる。
$pattern = array('/(.*?)(\(\s*(max|min)-width\s*:\s*\d+px\s*\))\s*(\d+px)\s*,\s*(.*?)/', '/(<img.*?)(calc\(\s*\d+px\s*\*\s*0.66\s*\)\s*,\s*)(\d+px)\s*[\"|\']/' );
$replace = array('$1$2 and (max-resolution:2dppx) $4, $2 and (min-resolution:3dppx) calc($4 * 0.66), $5', '$1$2(max-resolution:2dppx) $3, (min-resolution:3dppx) calc($3 * 0.66)"' );//置換
$image = preg_replace($pattern, $replace, $image1);

//preload記述を出力
echo $image;

//$imageが空なら空のままにする
if( empty($image) ) {
$image = '';
}
return $image;
}

?>

上記の関数にてcatch_preload_image();呼び出されるのは下記の記述。

■関数にて呼び出されるpreloadの画像例

<link rel="preload" as="image" href="https://example.com/img-001-1344x897.jpg" imagesrcset="https://example.com/img-001-672x449.jpg 672w, https://example.com/img-001-1344x897.jpg 1344w" imagesizes="(max-width:416px) and (max-resolution:2dppx) 384px, (max-width:416px) and (min-resolution:3dppx) calc(384px * 0.66), 1344px">

■header.phpの記述

<?php
//投稿ページだけに適応
if (is_single()){
//関数(preload記述呼び出し)
$img_preload = catch_preload_image();
if (!empty($img_preload)){
$img_preload;
}else{
}};
?>

<head>内のスタイルシートより上に上記の記述を入れる。

Menu