javascript  defer 属性の追加

Test how mobile-friendly your site is

最近、上記のGoogleの新しいモバイルサポートテストツールが発表になったりして、モバイル回りがざわめいています。

あんまり、低い点数だと妙に恥ずかしく感じる今日この頃、重い腰を上げて、script要素にdefer属性を付け始めました。

CSSと違って、script要素には、ハンドル名を示すid要素が降られていないので、まずは handle名を取得します。

functions.php

<?php
function inspect_script_handles() {
 global $wp_scripts;

 foreach( $wp_scripts->queue as $handle ) {
 echo $handle,' ';
 }
}
add_action( 'wp_print_scripts', 'inspect_script_handles' );
?>

このフィルターを使うと、ページの最上部にhandle 一覧が表示されますので、それらのハンドル名をつかって、script要素に defer属性を追加していきます。

functions.php (handleは、自身のサイトのscript handle名に置き換えてください)

add_filter('script_loader_tag', 'add_defer_script_loader_tag',10 , 2 );

function add_defer_script_loader_tag($tag, $handle){

 	if ( 'raindrops_slides'== $handle | | 'crayon_js'== $handle | | 'contact-form-7'== $handle | | 'jquery-ui-tooltip'== $handle ) {
		return str_replace( ' src', ' defer="defer" src', $tag );
	}

	return $tag;
}

関連:スタイルシート <link rel=”stylesheet” id=”style-css” … />を操作したい時

以下は、スタイルシートの属性値がシングルクウォートで囲まれているものを、ダブルクウォートに変更するフィルターです。

add_filter( 'style_loader_tag', 'nobita_quote_to_double' );

function nobita_quote_to_double( $return_value ) {

	return str_replace( "'", '"', $return_value );
}

'シングルクォーテーションを"ダブルクォーテーションで出力

一時的にスタイルを無効にする

わざわざフィルターを使うまでもなく、検証ツールで、disabledを追加すればいいだけですが、仮のurlを指定したり、ちょっとしたカスタマイズの計画を立てる時とか、利用シーンがあるかもしれません。

add_filter( 'style_loader_tag', 'nobita_style_disabled' , 10, 4 );

function 'nobita_style_disabled'( $html, $handle, $href, $media ) {
	
	if( 'bbp-default'== $handle ) {
		
		return "<link rel='stylesheet' id='$handle-css' href='$href' type='text/css' media='$media' disabled />\n";
	}
	return $html;
}
[emulsion_relate_posts]