Selectively Loading JavaScript and CSS Files in WordPress

If you’ve done any WordPress development, you’ve encountered a situation where you need to load custom JavaScript or CSS. Normally, you would do something like this:

function enqueue_scripts_styles() {
wp_enqueue_script('jquery');
wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery'));
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/assets/css/custom.css', array() );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts_styles' );

This code will load jQuery, then load our custom JavaScript after jQuery, then load our CSS.

This works great if you need the custom JavaScript and CSS on every page. But what if you only need the JavaScript and CSS only on a specific page? You don’t want to waste loading those files on every page.

To do so, you can use the following code:

function enqueue_scripts_styles() {
wp_enqueue_script('jquery');
if (is_page('your-page-slug')){
wp_enqueue_script('custom-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array('jquery'));
wp_enqueue_style('custom-style', get_stylesheet_directory_uri() . '/assets/css/custom.css', array() );
}
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts_styles' );

If you replace ‘your-page-slug’ with your actual page’s slug, you will only load the JavaScript and CSS on that specific page. This will save bandwidth and improve performance.

You could also use ‘is_category’ if you wanted to load JavaScript and CSS for a specific set of pages that were in a certain category.

Have any other WordPress questions? Leave a comment below.

One Comment

Edward Beckett March 31, 2015

To go a step further you can zip your scripts up too…

function zip_scripts() {

global $compress_scripts, $concatenate_scripts;

$compress_scripts = 1;
$concatenate_scripts = 1;

define(‘enforce_gzip’, true);

}

add_action(‘wp_enqueue_scripts’, ‘zip_scripts’);