clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

PHP function to load jQuery in WordPress footer

Filed under: WordPress/PHP— Tagged with: functions.php, jquery, snippets

Loading stuff on the footer, rather than in the header, makes your site load faster, because you move the blocking HTTP calls further down the page.

A word of caution: make sure that all your plugins work after this.

function load_jquery() {
  // Only use this method when not in wp-admin
  if (!is_admin()) {
    // Discover the correct protocol to use
    $protocol = 'http:';

    if ($_SERVER['HTTPS']=='on') {
      $protocol = 'https:';
    }

    // Settings for the script, change these to your liking
    // jQuery version you want
    $jquery_version = '2.0.3';
    // The url you want it from. Default to Google CDN
    $jquery_url = $protocol . '//ajax.googleapis.com/ajax/libs/jquery/' . $jquery_version . '/jquery.min.js';
    // Load in footer
    $footer_load = true;

    // Deregister the original version of jQuery
    wp_deregister_script('jquery');
    // Register the new version
    wp_register_script('jquery', $jquery_url, false, $jquery_version, $footer_load);
    // Add it back into the queue
    wp_enqueue_script('jquery');
  }
}

add_action('template_redirect', 'load_jquery');
add_action('wp_enqueue_scripts', 'my_scripts_method');

That goes into your themes functions.php file.

Further reading

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!