How to Optimize WooCommerce to Load Scripts and CSS Conditionally only if required?
WooCommerce and Online Shopping – One of the best thing happened for all WordPress users 🙂
It’s been almost a year WordPress acquired WooCommerce and it’s been amazing journey. It seems, currently WooCommerce covers nearly ~40% of all online stores
and that’s a big number. On Crunchify we wanted to have Online Digital Store and we have decided to give it a try.
WooCommerce comes as a simple plugin installation like any other plugin but it will be little bit heavy on resources.
Take a look a this:
WooCommerce adds total 13 new Database Tables
WooCommerce loads 3 CSS files and 5 JavaScript files on Each page
// CSS files woocommerce-layout.css woocommerce-smallscreen.css woocommerce.css // JavaScript files add-to-cart.min.js jquery.blockUI.min.js woocommerce.min.js jquery.cookie.min.js cart-fragments.min.js
Now as we know from Speed Optimization Goal, it’s absolutely not required to load all these 8 additional resources except cart
, checkout
or product
page. Loading these 8 extra files may slow down your blog which may create some negative impact Google Search Engine Result (SERP) page.
Here is a quick tips to disable all above scripts
except cart, checkout, my-account and product page.
//* Enqueue scripts and styles add_action( 'wp_enqueue_scripts', 'crunchify_disable_woocommerce_loading_css_js' ); function crunchify_disable_woocommerce_loading_css_js() { // Check if WooCommerce plugin is active if( function_exists( 'is_woocommerce' ) ){ // Check if it's any of WooCommerce page if(! is_woocommerce() && ! is_cart() && ! is_checkout() ) { ## Dequeue WooCommerce styles wp_dequeue_style('woocommerce-layout'); wp_dequeue_style('woocommerce-general'); wp_dequeue_style('woocommerce-smallscreen'); ## Dequeue WooCommerce scripts wp_dequeue_script('wc-cart-fragments'); wp_dequeue_script('woocommerce'); wp_dequeue_script('wc-add-to-cart'); wp_deregister_script( 'js-cookie' ); wp_dequeue_script( 'js-cookie' ); } } }
Put above code into your theme’s functions.php file and save
your changes.
And that’s it, you should be all good. Now try checking one more time on your blog home page and other posts and you shouldn’t see any of these files loaded on that page/post.