Wordpress: Enqueue jQuery in the Footer

I'm sure you read Scirra's Making A Fast Website (if not, you should probably stop reading this and head over there now...seriously, why are you still reading this?), which explains that the best place to put your <script> tags is in the footer, just before </body>. However, if you try to register a WordPress default script, such as jQuery, in the footer, the script will still be rendered to the <head> section during wp_head().

That's no good — you want to load jQuery during wp_footer(). No worries, there's a quick fix for that.

The Challenge

WordPress pre-registers default scripts to make your life easier. To load jQuery, this is all you need:

wp_enqueue_script( 'jquery' );

However, with the convenience comes a consequence: because jquery is already registered using wp_register_script(), we don't have the option to change that script's $in_footer parameter to true.

The Solution

Thankfully, there is a quick fix:

wp_deregister_script( 'jquery' ); //deregister and re-enqueue to load in footer
wp_enqueue_script( 'jquery',
    true );

And just like that, your site is fully optimized for maximum speed. Ok, maybe not fully optimized, but you're off to a good start.

Subscribe to 90 Degrees

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.