I have often found myself building a website where only one or two pages need some JavaScript functionality. It seems like a waste to load something like a Masonry library on every page when it may never be needed. Fortunately, conditionally loading a JavaScript in WordPress is pretty simple. First, though, if you are not familiar with loading JavaScript using WordPress’s wp_enqueue_script
function, you can learn more about that from the WordPress developer documentation. Here is an example of loading a masonry library through enqueueing:
wp_enqueue_script('masonry', get_stylesheet_directory_uri() . '/js/masonry.pkgd.min.js', array('jquery'), '1.0', true );
When we enqueue our scripts, we can use a PHP if statement to load scripts only when needed. There are a whole host of useful conditional tags in WordPress. You can find many of them in WordPress’s Theme Developer Handbook. In our use case above, we might want to load our masonry library for pages using a special template for masonry pages. Let’s say the filename for our template for masonry pages is page-masonry-gallery.php
. We can use WordPress’s is_page_template
conditional to enqueue our script just in these cases:
if( is_page_template( 'page-complete-gallery.php' ) ) {
wp_enqueue_script('masonry', get_stylesheet_directory_uri() . '/js/masonry.pkgd.min.js', array('jquery'), '1.0', true );
}
There are many other conditionals that would make sense to use. Perhaps you need some JavaScript just for a certain post type. is_single
has you covered. And you don’t need to limit yourself to built-in conditionals provided by WordPress, of course. You could look up the value of an Advanced Custom Field to determine if a script should be loaded. That way, an administrator for the site could determine if a script should be loaded on a page-by-page basis. The post_content
could also be scanned for a particular shortcode with has_shortcode
so that a plugin’s needed JavaScript is only loaded on pages utilizing its functionality.
It should also be said that this method can also be used to conditionally enqueue stylesheets as well. Using this approach can help slim down the unneeded assets you are loading with your WordPress site’s pages.