我想修复“消除首屏内容中的渲染阻止 JavaScript 和 CSS”要求以获得更好的PageSpeed Insights分数,但我不太确定解决此问题的最佳方法是什么。
- 如何最好地平衡新访问者和回访者的页面负载?
- 我什么时候应该异步加载我的 CSS,什么时候不?
- 我应该只对小屏幕使用内联 CSS 吗?
相关演示:优化关键渲染路径
例子
由于内联大量 CSS 会导致后续访问时页面加载速度变慢,因此我可以根据 cookie 为重复访问者提供不同的版本。为了检测首屏 CSS,我可以使用本文中的书签:paul.kinlan.me/detecting-critical-above-the-fold-css/
对于新访客:
<!DOCTYPE HTML>
<html>
<head>
<title>New Visitor</title>
<style><!-- insert above the fold css here --></style>
<noscript><link rel="stylesheet" href="style.css"></noscript>
</head>
<body>
<!-- insert content here -->
<script>
// load css
var node = document.createElement('link');
node.rel = 'stylesheet';
node.href = 'style.css';
document.head.appendChild(node);
// set cookie
var exp = new Date();
exp.setTime(exp.getTime() + 3600 * 1000);
document.cookie = 'returning=true; expires=' + exp.toUTCString() + '; path=/';
</script>
</body>
</html>
对于回访者:
<!DOCTYPE HTML>
<html>
<head>
<title>Returning Visitor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- content here -->
</body>
</html>
这种方法有什么问题吗?