Removing Woocommerce Scripts and CSS from Irrelevant Pages

If you’re running Woocommerce on a WP site, but don’t want the performance hit that the plugin adds with its multiple Javascript and CSS calls, you can use the code below to remove everything Woo-related from normal index, archive, single post and pages (including the generator tag).

Note that if you’re using Woocommerce widgets or have hardcoded cart information (ie, you show the cart on all pages, not just store pages), your results may vary.

// remove woocommerce scripts on unnecessary pages
function woocommerce_de_script() {
if (function_exists( 'is_woocommerce' )) {
if (!is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page() ) { // if we're not on a Woocommerce page, dequeue all of these scripts
wp_dequeue_script('wc-add-to-cart');
wp_dequeue_script('jquery-blockui');
wp_dequeue_script('jquery-placeholder');
wp_dequeue_script('woocommerce');
wp_dequeue_script('jquery-cookie');
wp_dequeue_script('wc-cart-fragments');
}
}
}
add_action( 'wp_print_scripts', 'woocommerce_de_script', 100 );
add_action( 'wp_enqueue_scripts', 'remove_woocommerce_generator', 99 );
function remove_woocommerce_generator() {
if (function_exists( 'is_woocommerce' )) {
if (!is_woocommerce()) { // if we're not on a woo page, remove the generator tag
remove_action( 'wp_head', array( $GLOBALS['woocommerce'], 'generator' ) );
}
}
}
// remove woocommerce styles, then add woo styles back in on woo-related pages
function child_manage_woocommerce_css(){
if (function_exists( 'is_woocommerce' )) {
if (!is_woocommerce()) { // this adds the styles back on woocommerce pages. If you're using a custom script, you could remove these and enter in the path to your own CSS file (if different from your basic style.css file)
wp_dequeue_style('woocommerce-layout');
wp_dequeue_style('woocommerce-smallscreen');
wp_dequeue_style('woocommerce-general');
}
}
}
add_action( 'wp_enqueue_scripts', 'child_manage_woocommerce_css' );

Up Next: How to Make a Facebook Icon Using Only CSS & HTML (no images)