How to Load CSS and JavaScript Only Where It’s Needed in WordPress
A slider script used on the homepage, a calculator on one landing page, animation code for the pricing page: if all of it loads on every page, every visitor pays for code they never run. Loading your own CSS and JavaScript only where it’s needed is one of the simplest speed wins.
This article is about your own code. To stop plugins loading their files everywhere, see how to disable scripts on specific WordPress pages.
The WordPress way: enqueue with conditions
Register files with wp_enqueue_script() and wp_enqueue_style(), and wrap them in a conditional:
add_action( 'wp_enqueue_scripts', function () {
$dir = get_stylesheet_directory_uri();
// Slider only on the front page.
if ( is_front_page() ) {
wp_enqueue_script( 'site-slider', $dir . '/js/slider.js', [], '1.0', true );
wp_enqueue_style( 'site-slider', $dir . '/css/slider.css', [], '1.0' );
}
// Calculator only on one page.
if ( is_page( 'mortgage-calculator' ) ) {
wp_enqueue_script( 'calculator', $dir . '/js/calculator.js', [], '1.0', true );
}
} );
The last argument true loads the script in the footer, so it doesn’t block the page from rendering.
Useful conditionals
| Condition | Where it loads |
|---|---|
is_front_page() | Homepage |
is_page( 'slug' ) | One page |
is_singular( 'product' ) | Every single product |
is_post_type_archive( 'product' ) | The product archive |
is_category( 'news' ) | One category archive |
has_block( 'core/gallery' ) | Pages that contain a gallery block |
has_block() is especially handy: load a script only on pages where the block that needs it is actually used.
Block assets load themselves
If the code belongs to a block, put it in that block’s block.json (style, viewScript). Block themes then load it only on pages where the block appears. Custom blocks built with FanCoolo WP work the same way: a block’s styles and View script travel with the block.
The no-code way
With Scripts Organizer, each code block (CSS, SCSS, JavaScript or PHP) has Template conditions:
- All (everywhere), or
- Page, Post: hand-pick single pages, posts or custom post type entries,
- Post Type: every page, every post, every product…,
- Taxonomy: category, tag or custom taxonomy archives.
Turn on Advanced Conditions – Exclude for “everywhere except…” rules, like all pages except the homepage, or all categories except Uncategorized. Add a schedule if the code is only needed for a while.
Check the result
Open a page where the code should not load, view the source (Ctrl+U) and search for the file name. Then check a page where it should load, and test that the feature works.
