Update on 7 Mar 2022: Follow this updated tutorial instead.
—
When you have a WooCommerce-powered shop in your WordPress site, assets like the following may be loading on all the pages of the site (depending on what plugins/services/theme are/is active):
woocommerce-layout.css
woocommerce-smallscreen.css
woocommerce.css
twenty-seventeen.css
add-to-cart.min.js
jquery.blockUI.min.js
js.cookie.min.js
woocommerce.min.js
cart-fragments.min.js
If you do not have a “Add to Cart” feature in your nav or site-wide WooCommerce widgets in a sidebar, it makes sense to have the assets load only on WooCommerce-related pages like the main Shop page, Cart page, Checkout page and My Account page.
This should help a little in lessening the site loading time to your visitors.
Add the following in your child theme’s functions.php or in a Code Snippet:
add_action( 'get_header', 'sk_conditionally_remove_wc_assets' );
/**
* Unload WooCommerce assets on non WooCommerce pages.
*/
function sk_conditionally_remove_wc_assets() {
// if WooCommerce is not active, abort.
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
// if this is a WooCommerce related page, abort.
if ( is_woocommerce() || is_cart() || is_checkout() || is_page( array( 'my-account' ) ) ) {
return;
}
remove_action( 'wp_enqueue_scripts', [ WC_Frontend_Scripts::class, 'load_scripts' ] );
remove_action( 'wp_print_scripts', [ WC_Frontend_Scripts::class, 'localize_printed_scripts' ], 5 );
remove_action( 'wp_print_footer_scripts', [ WC_Frontend_Scripts::class, 'localize_printed_scripts' ], 5 );
}
Source: https://gist.github.com/DevinWalker/7621777#gistcomment-1980453
References:
is_page( array( ‘my-account’ ) its better to use: is_account_page()
Ty. Used this in the updated article, https://wpdevdesign.com/how-to-remove-woocommerce-css-js-from-non-woocommerce-pages/.
This is not working it seems on latest WP+WooCommerce, can you confirm this still works?
Just published an updated article here: https://wpdevdesign.com/how-to-remove-woocommerce-css-js-from-non-woocommerce-pages/.