【发布时间】:2015-04-08 06:25:03
【问题描述】:
Google 建议 (https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery) 使用以下 JS 代码来优化页面速度(异步 CSS 加载)
<script>
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'small.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);
</script>
当我使用上面的代码时,Page Speed Insights (https://developers.google.com/speed/pagespeed/insights/) 会识别它并给页面更高的分数。但问题是,这段代码在旧版 IE 中不起作用。
例如,IE 8 会抛出错误“Object requestAnimationFrame is not defined”。问题很明显,IE 8 不支持 RAF,所以会因为未定义对象而抛出错误。
我需要网站在这些旧 IE 中也能正常运行,所以我决定更新我的代码如下:
<script>
function loadCss() {
var l = document.createElement('link');
l.href = 'http://static.xyz.com/css/style.min.css?v=23';
l.rel = 'stylesheet';
l.type = 'text/css';
l.media = 'screen';
document.getElementsByTagName('head')[0].appendChild(l);
}
if (typeof requestAnimationFrame === 'function') {
requestAnimationFrame(loadCss);
}
else if (typeof mozRequestAnimationFrame === 'function') {
mozRequestAnimationFrame(loadCss);
}
else if (typeof webkitRequestAnimationFrame === 'function') {
webkitRequestAnimationFrame(loadCss);
}
else if (typeof msRequestAnimationFrame === 'function') {
msRequestAnimationFrame(loadCss);
}
else if (typeof window.addEventListener === 'function') {
window.addEventListener('load', loadCss);
}
else {
window.onload = loadCss;
}
这段代码不是很漂亮,但它在 IE7+、Firefox、Chrome 等中都能正常运行。但是当我通过 Page Speed Insights 测试它时,它无法识别 CSS 是异步加载的,也没有给我更高的分数(它显示的错误与 CSS 是通过 同步加载的一样)。
我的问题是:我的代码中是否存在我不知道的错误,或者 Google 根本无法识别这种插入异步 CSS 的方式。代码正常运行对我来说绝对重要,但我希望在 Page Speed 测试中获得更高的分数,因为这对 SEO 有好处。
我不是 Javascript 方面的专家,也不是布局绘画之类的专家,但我找不到关于发生了什么或问题出在哪里的解释。
提前感谢您提供的任何解释或提示。
【问题讨论】:
-
你绝对需要异步加载 css 吗?
-
不,我不知道,这不是绝对必要的。但我希望能够异步加载它,只要它可以工作并且 Google 会识别它。
-
requestAnimationFrame 被所有没有前缀的浏览器所支持,所以你并不需要 mozRequestAnimationFrame、webkitRequestAnimationFrame 和 msRequestAnimationFrame。我还觉得对于较旧的 IE 浏览器 [唯一不支持 requestAnimationFrame 的浏览器],直接 loadCSS() 而不等待 onload 可能是一个更好的主意。所以 if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(loadCss); } 其他 { loadCss();}
-
@MatejHostak 我有同样的问题。你找到解决办法了吗?
-
还没有,但如果我找到解决方案,我会发布更新。
标签: javascript html css pagespeed