Load-on-demand is a very important principle in website front-end optimization, but the front-end resources provided by WooCommerce do not follow this principle well. Although WooCommerce has separated some CSS, but the separation is not reasonable, which leads to a lot of unnecessary CSS in the page.
For websites that use the default WooCommerce styles, there may be no problem with this setup. But if we need to make a more elaborate websitecustom developmentIf you put all this CSS in one file, the file will quickly become very large, affecting the rendering speed of the page.
Loading CSS Code on Demand with WooCommerce Judgment Functions
To avoid this problem, we can segregate the CSS used in the WooCommerce site on a page-by-page basis, loading it according to the page it is displayed on. On the shopping cart page, load the CSS needed for the shopping cart, and on the checkout page, load the CSS needed for the checkout page, and so on. On the home page, product list page, and product detail page, you don't need to load these unnecessary CSS, which can speed up the opening speed of these pages to a certain extent.
WooCommerce provides us with some very useful judgment function to help us determine what type of page is currently displayed, the following is the template code we use in some of the themes, the need for friends can refer to.
// Product Listing Page
if (is_product() || is_shop() || is_product_category() || is_product_tag()) {
wp_enqueue_style('_s-woocommerce-checkout', _s_asset('styles/products.css')); }
}
// Product details page
if (is_singular('products')) {
wp_enqueue_style('_s-woocommerce-review', _s_asset('styles/review.css')); }
}
// Shopping 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')); }
}
Similar to WooCommerce, in fact, we can also do this in WordPress, in the home page, the list page, the post page to load their respective pages need CSS, provided that we need to be reasonable separation of the CSS of these pages. In addition to loading CSS on demand through the back-end, there are also some front-end methods to achieve this function, the specific will not expand the discussion, interested friends can search for their own research.