You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止WooCommerce加载冗余Inter字体以优化页面速度

问题描述

在WordPress站点使用WooCommerce时,发现它加载了Inter-VariableFont_slnt,wght.woff2大字体文件,体积接近整页大小,严重拖慢加载速度并阻塞FCP。当前主题Uncode已加载所有所需字体,无需WooCommerce额外加载字体。

已尝试的操作

  • 在Uncode主题设置中启用了“Disable WC Blocks Style”选项;
  • 添加以下PHP代码停用WooCommerce区块样式和字体资源,但字体仍在加载:
function remove_woocommerce_font_styles() {
    wp_dequeue_style('wc-blocks-vendors-style');
    wp_dequeue_style('wc-blocks-style');

    if (wp_style_is('wp-fonts-local', 'enqueued')) {
        wp_dequeue_style('wp-fonts-local');
    }
}
add_action('wp_enqueue_scripts', 'remove_woocommerce_font_styles', 20);
  • 已清除所有缓存,但产品页面仍加载该字体。

补充信息

该字体通过ID为wp-fonts-local的内联<style>块添加:

<style id="wp-fonts-local" type="text/css">
@font-face{font-family:Inter;font-style:normal;font-weight:300 900;font-display:fallback;src:url('https://example.com/wp-content/plugins/woocommerce/assets/fonts/Inter-VariableFont_slnt,wght.woff2') format('woff2');font-stretch:normal;}
@font-face{font-family:Cardo;font-style:normal;font-weight:400;font-display:fallback;src:url('https://example.com/wp-content/plugins/woocommerce/assets/fonts/cardo_normal_400.woff2') format('woff2');}
</style>

需求

彻底阻止WooCommerce加载该字体文件,不使用JavaScript在页面加载后移除(仍会下载字体),需要干净的停用或阻止加载方法。


解决方案

之前的方法无效是因为wp-fonts-local并非通过常规wp_enqueue_style注册的样式,而是WooCommerce通过woocommerce_enqueue_fonts动作直接输出的内联样式。可以通过移除这个动作从根源上阻止字体加载:

方法1:全局禁用WooCommerce字体加载

将以下代码添加到主题的functions.php文件,或使用自定义代码插件:

// 彻底移除WooCommerce的字体加载动作
add_action('init', function() {
    remove_action('wp_enqueue_scripts', 'woocommerce_enqueue_fonts');
    remove_action('admin_enqueue_scripts', 'woocommerce_enqueue_fonts');
}, 10);

这段代码会在初始化阶段移除WooCommerce用于输出字体样式的动作,直接阻止内联@font-face代码生成,也就不会触发字体文件的下载。

方法2:仅在特定页面禁用(可选)

如果只需要在前端产品页面或特定页面禁用,可调整代码为:

add_action('wp_enqueue_scripts', function() {
    // 仅在产品页面禁用字体加载
    if (is_product()) {
        remove_action('wp_enqueue_scripts', 'woocommerce_enqueue_fonts', 10);
    }
}, 9);

注意这里的优先级设为9,确保在WooCommerce添加动作之前执行移除操作。

验证方式

添加代码后,清除网站缓存和浏览器缓存:

  • 查看页面源代码,确认ID为wp-fonts-local的内联<style>块已消失;
  • 打开浏览器开发者工具的「网络」面板,确认不再加载Inter-VariableFont_slnt,wght.woff2和cardo_normal_400.woff2文件。

内容的提问来源于stack exchange,提问作者Robin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 00:11:08