javascript-具有多个CSS文件的Google PageSpeed Insights
作者:互联网
我正在根据Google的PageSpeed Insights优化我的网站.建议为多个文件“优化CSS传递”(例如,简化名称):
<link rel="stylesheet" href="css/app.css" type="text/css">
<link rel="stylesheet" href="css/responsive.css" type="text/css">
<link rel="stylesheet" href="css/styles.css" type="text/css">
…通过将它们从< link>中移出< head>中的标签在结束标记之前通过JavaScript调用:
<script>
var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'css/app.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>
< / body>
如您所见,仅app.css被调用.
我的问题是,有没有办法在此脚本中添加所有三个CSS文件?
解决方法:
您将需要扩展Google的脚本,以便可以添加多个文件,如下所示:
var loadCSSFiles = function() {
var links = ["style1.css", "style2.css", "style3.css"],
headElement = document.getElementsByTagName("head")[0],
linkElement, i;
for (i = 0; i < links.length; i++) {
linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
linkElement.href = links[i];
headElement.appendChild(linkElement);
}
};
var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) {
raf(loadCSSFiles);
} else {
window.addEventListener("load", loadCSSFiles);
}
标签:pagespeed,css,javascript 来源: https://codeday.me/bug/20191028/1952985.html