How to Conditionally Load All WooCommerce Styles & Scripts

June 11, 2019

In this short post I’ll be sharing a PHP code snippet to conditionally load WooCommerce styles and scripts within your WordPress website. WooCommerce by default loads all it’s Javascript and CSS files on every single page of your site.

This unnecessary loading of resources on every page load results in slower loading times.

Unless you make use of site-wide WooCommerce widgets, such as the cart navbar item, you can simply stop loading these resources on every page.

For example, you’ll want to load this stuff on product pages, product archives, the checkout page and so on. But you wouldn’t need it on a contact page.

Luckily there’s an easy way to do this. You can conditionally load the WooCommerce stylesheets and scripts only on pages where it’s absolutely needed, using some straightforward PHP code shown below.

Add this code to your functions.php

To get started, open up your functions.php file and add the code snippet below. You won’t need to edit anything and it should work right away.

Tested with WooCommerce versions 3.6.x and WordPress 5.2.x.

 * Conditionally load WooCommerce styles and scripts.
function conditionally_load_woocommerce_styles_scripts() {
  // Check for active WooCommerce plugin
  if( function_exists( 'is_woocommerce' ) ){
    // Check for WooCommerce pages
    if(!is_woocommerce() && !is_cart() && !is_checkout() && !is_page(array('my-account'))) { 		
      // Dequeue all WooCommerce styles

      // Dequeue all WooCommerce scripts
add_action( 'wp_enqueue_scripts', 'conditionally_load_woocommerce_styles_scripts' );

You can see if the code has worked by checking the source code of your website. Do a search for ‘WooCommerce’ and you shouldn’t find any .js or .css files.

Did this work for you?

Let me know in the comments if this code worked for you. If not, let me know what version of WordPress and WooCommerce you are running.

Some code has been taken from the WooCommerce documentation.