PageSpeed Insightsの「レンダリングを妨げるリソースの除外」という項目で、jquery.min.jsが指摘されたときの対策をご紹介。
所要時間は約5分といったところ。
jqueryを読み込んでいるlinkタグに、async属性を追加して、非同期で読み込ませると、指摘された項目を改善することができます。
それではさっそく結論。
WordPressテーマの子テーマのfunctions.phpに以下コードを追記しましょう。
※SANGOテーマを使っている方向け
▼▼▼
sango-theme-child/functions.php
add_filter('script_loader_tag', 'add_async', 10, 2);
function add_async($tag, $handle) {
if($handle !== 'jquery') {
return $tag;
}
return str_replace(' src=', ' async src=', $tag);
}
▼▼▼
SANGOテーマでは、library/functions/sng-style-scripts.phpの31行あたりで以下のコードを使いgoogleのCDNでjqueryを読み込んでいます。
▼▼▼
sng-style-scripts.php
wp_enqueue_script('jquery','https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js',array(), '', false);
上記のコードに直接async属性を追記することはできないので、先程紹介したようにscript_loader_tagフックを利用するんです。
functions.phpを編集し終わったらFTPでファイルをアップしてキャッシュを消してから再度PageSpeed Insightsで確認してみましょう!
MEMO
この変更で警告は消えると思いますが、ぼくの場合、変更を加えるよりも少しスコアが下がってしまったので自己責任でお願いいたします。参考:WordPress wp_enqueue_scriptで追加するscriptタグにdefer/asyncを付加する方法
次はこの記事!






