Generally, it’s a good idea to include JavaScript / jQuery libraries and plugins at the bottom of the page, just before closing the body
tag. The reason is pretty simple, HTTP/1.1 specification suggests that browsers not download more than two assets in parallel.
Using wp_enqueue_script
is the best way to load JavaScript
and jQuery
into your WordPress template. It allows for greater control of when and where JS loads on your site. Here is a quick hook I’m using in my Genesis Framework theme for right sidebar sticky follow section. Add below code to your child theme’s functions.php file.
// Enqueue sticky menu script - Crunchify Tips add_action( 'wp_enqueue_scripts', 'crunchify_enqueue_script' ); function crunchify_enqueue_script() { wp_enqueue_script( 'follow', get_stylesheet_directory_uri() . '/js/follow.js', array( 'jquery' ), '', true ); }
In your Child Theme’s folder, create another folder called js
, and then create a new file called follow.js
and place that inside. This file includes the jQuery that will control the position of the sidebar follow section. Here’s what the path should look like:
child-theme-directory/js/follow.js
Additional Speed Optimization Tips:
In below code snippets we have unregistered the default jQuery library from default WordPress, then added the Google CDN version after closing the footer tag.
Using the Google CDN-hosted version of jQuery is another performance gain, because it will be cached for any visitors who have loaded another site that uses the same version. Just put below code to theme’s functions.php file.
/** Remove jQuery and jQuery-ui scripts loading from header */ add_action('wp_enqueue_scripts', 'crunchify_script_remove_header'); function crunchify_script_remove_header() { wp_deregister_script( 'jquery' ); wp_deregister_script( 'jquery-ui' ); } /** Load jQuery and jQuery-ui script just before closing Body tag */ add_action('genesis_after_footer', 'crunchify_script_add_body'); function crunchify_script_add_body() { wp_register_script( 'jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js', false, null); wp_enqueue_script( 'jquery'); wp_register_script( 'jquery-ui', 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js', false, null); wp_enqueue_script( 'jquery-ui'); }
If you’re having issues with the code above, I’m happy to give assistance!
How to verify?
After making above changes just check HTML element of your site. Right click
on blog and click Inspect Element
. You should see jQuery script loaded successfully as you see below.
