Skip to main content

Tối ưu hóa WooCommerce bằng cách xóa Javascript và CSS không cần thiết

Để tối ưu cho website WooCommerce - Wordpress, sau đây sẽ hướng dẫn xóa những đoạn script and css không cần thiết hoặc hiển thị khi cần thiết mà thôi.

Giới thiệu về WooCommerce 

WooCommerce là plugin đơn giản như bất kỳ plugin nào khác dành cho các website bán hàng online chạy bằng CMS WordPress nhưng nó sẽ hơi nặng về khi load đầy đủ các chi tiết. 

WooCommerce  có tổng cộng 13 bảng trong database

Image
WooCommerce-với tổng số 13 bảng database



WooCommerce cần load 3 file CSS và 5 file JavaScript cho mỗi trang


// 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

Giải pháp tối ưu cho WooCommerce

Đôi khi một số website không sử dụng hết 8 file bổ sung này, vậy nên xóa hoặc tắt nó đi sẽ giúp cải thiện đáng kể trang website của chung ta.

Dưới đây là mẹo nhanh để tắt tất cả các file trên ngoại trừ giỏ hàng, thanh toán, tài khoản và trang sản phẩm.

Đặt hết tất cả đoạn code dưới vào file functions.php trong theme của bạn và lưu lại.

//* 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' );
 
		}
	}	
}

Cuối cùng hãy reload và check lại trên