Reputation: 10240
Setting the $in_footer
parameter to true
in wp_enqueue_script loads a script in the footer. This is great if I'm adding a new script. However, WordPress already provides a version of jQuery by default and this is enqueued in the document head.
How can I move the jQuery provided by WordPress from the header to the footer?
Upvotes: 0
Views: 2806
Reputation: 1647
Maybe the defer
attribute will help. There is a good article on this topic.
I use the following code for convinient nonblocking loading of any scripts, not just jQuery.
// Defer scripts.
function dt_add_defer_attribute( $tag, $handle ) {
$handles = array(
'jquery-core',
'jquery-migrate',
'fancybox',
);
foreach( $handles as $defer_script) {
if ( $defer_script === $handle ) {
return str_replace( ' src', ' defer src', $tag ); // Or ' async src'
}
}
return $tag;
}
add_filter( 'script_loader_tag', 'dt_add_defer_attribute', 10, 2 );
Upvotes: 0
Reputation: 3491
You need to de-register the existing query and re-register it to load in the footer.
function jquery_in_footer() {
if (!is_admin()) {
wp_deregister_script('jquery');
// load the local copy of jQuery in the footer
wp_register_script('jquery', home_url(trailingslashit(WPINC) . 'js/jquery/jquery.js'), false, null, true);
wp_enqueue_script('jquery');
}
}
add_action('init', 'jquery_in_footer');
Bear in mind that if you have any other scripts enqueued that depend on jQuery and are not loaded in the footer, WordPress will still load jQuery in the header to satisfy that dependency.
(adapted from http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/)
Edit: If you really want to get crazy, you could modify the WP_Scripts object directly, but then you're dependent on the implementation never changing. I imagine that would change before they even thought of moving jquery.js' location in wp-includes :)
But just for fun…
function load_jquery_footer() {
global $wp_scripts;
$wp_scripts->in_footer[] = 'jquery';
}
add_action('wp_print_scripts', 'load_jquery_footer');
Upvotes: 2