trying to change the world, on a budget

The Secret to Enqueuing Scripts in the WordPress Footer

WordPress offers the enqueue_scripts feature, which allows theme developers to carefully manage their script dependencies and versions.  Here’s the syntax:

First your register your script -

<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Then enqueue it, and pass it the handle that you gave it:

wp_enqueue_script( 
     $handle
    ,$src
    ,$deps
    ,$ver
    ,$in_footer 
);

This is a neat system, and it even offers the ability to put the scripts in your header or your footer, with the $in_footer argument. This is great for optimizing your site’s load time.

Theoretically, this would be like:

<?php  

wp_register_script( ‘my_script’, $script_path );
wp_enqueue_script( ‘my_script’, false, false, false, true );

?>

Except that $in_footer doesn’t work like that.

This was very frustrating for me, as I did everything like the Codex said – and got the script loading fine in the head. But no matter what I set $in_footer to, I couldn’t get the script to move to the footer.

The Codex doesn’t explain this, as far as I can see. It was only after scouring the interwebs, that I found the answer:

The $in_footer flag does not work if you register the script ahead of time.  

Yes that’s right, a WordPress feature does not work if you follow WordPress best practice. Imagine that.

Instead of registering your script ahead of time, name it on the fly when you run wp_enqueue_script:

<?php wp_enqueue_script( ‘my_script’, $script_path, false, false, true ); ?>

And voila, your script will load in the footer!  (A big thank you to Cloud Four for their blog post!)