Mat*_*tak 7 html javascript css pagespeed
Google建议使用以下JS代码(https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery)来优化网页速度(异步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>
Run Code Online (Sandbox Code Playgroud)
当我使用上面的代码时,Page Speed Insights(https://developers.google.com/speed/pagespeed/insights/)会识别它并为页面提供更高的分数.但问题是,这段代码在旧的IE中不起作用.
例如,IE 8抛出错误"未定义对象requestAnimationFrame".问题很明显,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;
}
Run Code Online (Sandbox Code Playgroud)
这段代码不是那么漂亮,但它可以在IE7 +,Firefox,Chrome等中正常运行.但是当我通过Page Speed Insights进行测试时,它无法识别CSS是异步加载的并且不会给我更高的分数(它显示与通过同步加载CSS相同的错误).
我的问题是:我的代码中是否存在错误,我不知道,或者Google根本无法识别这种插入异步CSS的方式.对我来说绝对重要的是,代码工作正常,但我想在Page Speed测试中获得更高的分数,因为这对于SEO目的是有益的.
我不是Javascript的专家,也不是布局绘画和类似的东西,但我无法找到正在发生的事情或问题所在的解释.
提前感谢任何解释或提示要寻找什么.