In WordPress themes and plugins, the recommended way to load JavaScript is with wp_enqueue_script(). That function lets us declare dependencies, specify version numbers, and choose whether the script loads in the page header or footer. It is flexible and convenient.
What it does not provide directly is a “load this script only on these specific pages” parameter. Fortunately, WordPress gives us enough conditional logic that we can implement that behavior ourselves.
Why load JavaScript only on specific pages?
If a large JavaScript library is only needed on one page or a small group of pages, there is no reason to force every page on the site to load it. Otherwise, pages that do not use that functionality still pay the performance cost of downloading and parsing unnecessary scripts.
For example, imagine a theme with a page template named Portfolio Archive. That template might depend on libraries such as imagesloaded, masonry, isotope, and jquery-ias. Those libraries are useful there, but meaningless on the rest of the site.
Load a script only when a page uses a specific page template
The following code loads common scripts for every page, then checks whether the current page uses a specific page template. If it does, the extra JavaScript libraries needed by that template are loaded.
// Register the loading function on the hook
add_action('wp_enqueue_scripts', 'my_theme_load_scripts');
// Load styles and scripts
function my_theme_load_scripts(){
wp_enqueue_script('jquery');
// JavaScript file needed on every page
wp_enqueue_script('my_second_script', get_template_directory_uri() . '/js/main.js');
if(is_page()){ // Check the current page
global $wp_query;
// Whether the page uses a specific page template
$template_name = get_post_meta( $wp_query->post->ID, '_wp_page_template', true );
if($template_name == 'portfolio-archive.php'){
// If that page template is active, load the required libraries
wp_enqueue_script('my_third_script', get_template_directory_uri() .'/js/imagesloaded.js');
...
}
}
}
In real-world WordPress theme development, not every theme needs this level of granularity. If a theme only has a small number of scripts, bundling them together may still be the better option because it reduces requests and makes browser caching easier. The right choice depends on the size of the site and how widely each script is actually used.
