如何從不需要 WooCommerce 的頁面中刪除 WooCommerce CSS 樣式和 js 腳本

如何從不需要 WooCommerce 的頁面中刪除 WooCommerce CSS 樣式和 js 腳本

WooCommerce 在每個頁面上加載三個核心 CSS 樣式表,並在 WordPress 站點上安裝時發布。通過從不需要它的頁面和內容中刪除樣式和腳本,可以節省一些頁面加載時間。

它還從它用於其功能的庫中加載了一堆其他 javascripts 和 CSS 樣式。

以下是如何以不同方式加載這些文件,以便它們僅出現在您需要的頁面上,從而加快非 Woo​​Commerce 內容的頁面加載時間。

  • woocommerce-layout.css
  • woocommerce-smallscreen.css
  • woocommerce.css

這些是從 /wp-content/plugins/woocommerce/assets/css/ 加載的

Woo 已經使用過濾器來刪除所有 3 個或刪除單個過濾器。

// Remove each style one by one
add_filter( 'woocommerce_enqueue_styles', 'jk_dequeue_styles' );
function jk_dequeue_styles( $enqueue_styles ) {
	unset( $enqueue_styles['woocommerce-general'] );	// Remove the gloss
	unset( $enqueue_styles['woocommerce-layout'] );		// Remove the layout
	unset( $enqueue_styles['woocommerce-smallscreen'] );	// Remove the smallscreen optimisation
	return $enqueue_styles;
}
// Or just remove them all in one line
add_filter( 'woocommerce_enqueue_styles', '__return_false' );

你可以這樣做,只需添加自己的 CSS 樣式

add_action( 'wp_enqueue_scripts', 'wp_enqueue_woocommerce_style' );
function wp_enqueue_woocommerce_style(){
	wp_register_style( 'mytheme-woocommerce', get_stylesheet_directory_uri() . '/css/woocommerce.css' );
	
	if ( class_exists( 'woocommerce' ) ) {
		wp_enqueue_style( 'mytheme-woocommerce' );
	}
}

這很棒,但它仍會在每個頁面上加載,如果您將 WooCommerce 保留在默認頁面上,則可以有條件地加載 CSS 文件。

add_action('wp_enqueue_scripts','wpb_load_woocommerce');
function wpb_load_woocommerce() {
if( is_page(array( 'shop', 'cart', 'checkout' ) ) or 'product' == get_post_type() ) {
	wp_enqueue_style( 'wpb-woo', get_stylesheet_directory_uri() . '/css/woocommerce.css',  '', '3', 'all');		
	}
}

另一種僅在 WooCommerce 產品和商店頁面上加載 CSS 樣式和 Javascripts 的好方法是在所有其他頁面上將它們出列。

add_action( 'template_redirect', 'remove_woocommerce_styles_scripts', 999 );
function remove_woocommerce_styles_scripts() {
    if ( function_exists( 'is_woocommerce' ) ) {
        if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() ) {
            remove_action('wp_enqueue_scripts', [WC_Frontend_Scripts::class, 'load_scripts']);
	    remove_action('wp_print_scripts', [WC_Frontend_Scripts::class, 'localize_printed_scripts'], 5);
	    remove_action('wp_print_footer_scripts', [WC_Frontend_Scripts::class, 'localize_printed_scripts'], 5);
        }
    }
}

這裡所有的 Woo 樣式和腳本都是通過在頁面加載之前掛鈎到’template_redirect’ 的最後一個鉤子並刪除所有樣式和腳本的初始 Woo add_action 來刪除的。

文章沒看懂?代碼不會用?需要幫助您可以去論壇提問自助服務台

作者小新

大象、大象 ,你的鼻子怎麼那麼長 ,媽媽說鼻子長才是漂亮 ......