Unload Plugin Assets Except on the Pages That Need Them
Removes the scripts and styles you list from every page except the ones you choose, for plugins that load their files site-wide.
Opens WPIDE on
Code
// 'script:handle' or 'style:handle' => page IDs or slugs where the file is still needed.
$wpide_assets_only_on = array(
'style:some-gallery-style' => array( 'gallery' ),
'script:some-booking-script' => array( 'book-now', 42 ),
);
$wpide_unload_assets = function () use ( $wpide_assets_only_on ) {
foreach ( $wpide_assets_only_on as $asset => $pages ) {
list( $type, $handle ) = array_pad( explode( ':', $asset, 2 ), 2, '' );
if ( '' === $handle || ( $pages && ( is_page( $pages ) || is_single( $pages ) ) ) ) {
continue;
}
if ( 'script' === $type ) {
wp_dequeue_script( $handle );
} else {
wp_dequeue_style( $handle );
}
}
};
add_action( 'wp_enqueue_scripts', $wpide_unload_assets, 999 );
add_action( 'wp_print_footer_scripts', $wpide_unload_assets, 1 );
Notes
Find handles in the page source (id="HANDLE-css" or id="HANDLE-js") and test the pages that still need them.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.