WordPressのwp_enqueue_scriptで呼びだすJavaScriptファイルをフッター(wp_footer()内)に呼びだす方法

Ads
WordPress

ご質問頂いたのと、ググっても
あんまり情報を見かけなかった
ので以外と知らない方もいるか
もしれない、と思ったので書いて
みます。JSファイルをフッターに
呼びだす方法。

土曜日なので軽い話題です。

WordPressで、wp_enqueue_scriptでJavaScriptファイルを呼び出しているけど、普通に書くとwp_head()内に読み込まれます。でも、JavaScriptは下部に置いた方が表示スピードに与える影響も減らせるらしいから、フッターに呼び出したい。どうすればいいのかな?みたいなご質問を頂戴しました。

wp_enqueue_scriptでwp_footer()内に呼びだす

まず、wp_head()内に呼びだすコードは以下の通りです。

wp_enqueue_script('jquery', 'http://example.com/foo.js', array(), '1.0');

このfoo.jsというファイルをwp_footer()内に呼び出すには以下のようにtrueパラメーターを書いてあげればいいだけです。

wp_enqueue_script('jquery', 'http://example.com/foo.js', array(), '1.0', true);

本家Docにも以下のように記載されています。

$in_footer
(boolean) (optional) Normally scripts are placed in the section. If this parameter is true the script is placed at the bottom of the . This requires the theme to have the wp_footer() hook in the appropriate place. Note that you have to enqueue your script before wp_head is run, even if it will be placed in the footer.
Default: false

いい加減な翻訳で申し訳無いですけど、「$in_footerパラメーターがtrueになっている際にwp_footer()の適切な箇所にフックします。デフォルトはfalseです。」と書いてありますね。何も書かなければfalseなのでwp_head()に読み込まれます。

以上です。1人の方にでも参考になれば幸いです。

タイトルとURLをコピーしました