
Load CSS on Demand in WooCommerce to Optimize Frontend Performance
In frontend optimization, loading resources on demand is a very important principle.
However, WooCommerce’s default way of handling frontend resources doesn’t strictly follow this principle. Although WooCommerce has separated some CSS files, the separation isn’t very well-organized. As a result, many unnecessary CSS files are loaded on pages where they’re not needed.
If you are using WooCommerce’s default styles without much customization, this setup might not cause any major issues.
Load WooCommerce CSS Selectively Using Conditional Functions
To solve this problem, we can separate CSS based on different pages and only load what is necessary.
For example:
- Load the cart-related CSS only on the cart page.
- Load checkout-related CSS only on the checkout page.
- On the homepage, product list, or product detail pages, skip loading unnecessary cart or checkout CSS.
But if you are doing custom development or fine-tuning your site’s design, you will likely add a lot of your own CSS. If everything is dumped into one large CSS file, that file can quickly become bloated and will slow down the rendering of your pages.
This method can significantly improve the loading speed of important pages like the homepage or product catalog. WooCommerce actually provides very useful conditional functions that help us easily detect the type of page being displayed.
Below are some example codes I often use in custom themes to achieve this. You can easily adapt them to your project:
// Product list pages
if (is_product() || is_shop() || is_product_category() || is_product_tag()) {
wp_enqueue_style('_s-woocommerce-products', _s_asset('styles/products.css'));
}
// Single product page
if (is_singular('product')) {
wp_enqueue_style('_s-woocommerce-review', _s_asset('styles/review.css'));
}
// Cart page
if (is_cart()) {
wp_enqueue_style('_s-woocommerce-cart', _s_asset('styles/cart.css'));
}
// Checkout page
if (is_checkout()) {
wp_enqueue_style('_s-woocommerce-checkout', _s_asset('styles/checkout.css'));
}
// Account page and Order Received page
if (is_account_page() || is_order_received_page()) {
wp_enqueue_style('_s-woocommerce-account', _s_asset('styles/account.css'));
}
This same idea can be applied not just to WooCommerce but across the entire WordPress site.
You can load specific CSS only for the homepage, category pages, single post pages, etc.
The key is to separate your CSS files carefully so that each page type has its own lightweight styles.
Of course, besides backend methods, there are also frontend techniques (like JavaScript-based dynamic loading) to achieve similar results. But that’s beyond the scope of this article — if you’re interested, feel free to research further!