【问题标题】:Google fonts + Pagespeed makes it blinkGoogle fonts + Pagespeed 让它闪烁
【发布时间】:2026-01-23 17:55:01
【问题描述】:

我的第一个解决方案是像这样添加 Google 字体:

<link href='http://fonts.googleapis.com/css?family=Open+Sans:300|Abel|Arimo:400,700' rel='stylesheet' type='text/css'>

然后我被谷歌页面速度击中。

Google Pagespeed 说我应该异步加载字体。所以我做了并且它有效。现在字体在加载整个页面之前不会加载。

<script type="text/javascript">
WebFontConfig = {
  google: {
    families: [ 'Open+Sans:300', 'Abel', 'Arimo:400,700' ]
  },
  active: function() {

  },
};

/* async! */
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>

缺点是由于字体加载的延迟,我得到了一个字体“闪烁”。真的需要这样吗?还是有第三种解决方案?

【问题讨论】:

    标签: javascript fonts seo google-font-api


    【解决方案1】:

    似乎没有什么好的方法可以防止第一次加载时闪烁,因为在页面已经启动之前字体不会到达那里。

    处理它的最佳方法似乎是使用某种标志,通过 cookie 或 sessionStorage,让浏览器知道尽可能使用缓存副本。

    有一篇很好的文章here。祝你好运!

    【讨论】: