admin管理员组文章数量:1530873
场景
假如我们有一个网站,样式多样,所以样式文件也会很大。
出现问题
浏览器的渲染顺序是等head中的css资源解析加载完成后浏览器才会渲染页面。这个时候如果css文件太大,那么在首次渲染的时候会出现一段白屏,用户体验极不好。这个时候我们就要考虑怎么样更快的实现首屏渲染,使得用户体验好点呢?
解决大概思路
如果我们把样式分为两份,一份为首屏渲染的样式,一份为剩余页面的样式。使得首屏的样式内联在head里面,当输入url,浏览器解析到html文件就尽快的渲染页面,解决白屏的问题。对于其他页面的样式可以等待首屏加载完后再异步加载。这样子貌似可以解决白屏的问题,那让我们来试试~~
解决具体实现
首先我们要分析一下DOM结构哪些css是首页渲染必须的,这个时候查了一下文档,有多种自动化处理的工具。
Critical是一个node的第三方库,帮助我们自动筛选critical css(也就是自动筛选首页需要的css集合然后以内联的方式写入到head中)
那么应该怎么使用呢?这里我们结合grunt+critical来实现一下。
1. 新建一个文件夹:
- npm init 增加package.json文件
- 新建page.html,为原文件
<!--page.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>critical css</title>
<link rel="stylesheet" type="text/css" href="../css/page.css"></link>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>
/*page.css*/
body {
background: #f5f5f5;
color: #fff;
}
h1 {
font-size: 16px;
color: #0f0;
}
h2 {
font-size: 14px;
color: #f00;
}
- 新建Gruntfile.js,为grunt配置文件
module.exports = function(grunt) {
grunt.initConfig({
critical: {
dist: {
options: {
base: './',
dimensions: [
{
width: 1200,
height: 800
},
{
width: 800,
height: 600
}
]
},
src: 'page.html',
dest: 'result.html'
}
}
});
grunt.loadNpmTasks('grunt-critical');
grunt.registerTask('default', ['critical']);
}
2. 然后进入目录安装依赖:
npm install grunt grunt-critical --save
3. 安装成功后,执行:grunt命令,会生成一个result.html文件,我们发现head中多了一个内联样式,并异步加载了剩余的样式。
好了,解决了,另外它还可以:
- 配置不同的屏幕尺寸,在options里面多了一个dimensions属性,值为一个数组可以设置多个屏幕尺寸
dimensions: [
{width: 1200, height: 800},
{width: 800, height: 600}
]
- 如果是对多个文件进行处理需要在dist属性里面增加一个files属性,值为一个数组
files: [
{ src: './public/index1.html', dest: 'dist/indexRes1.html'},
{ src: './public/index2.html', dest: 'dist/indexRes2.html'},
{ src: './public/index3.html', dest: 'dist/indexRes3.html'},
{ src: './public/index4.html', dest: 'dist/indexRes4.html'},
{ src: './public/index5.html', dest: 'dist/indexRes5.html'}
...
]
或者使用以下方式配置整个目录下的文件:
options: {
src: '*.html',
dest: 'dist/'
}
但是它还存在弊端:
- 每次修改首页样式都要重新执行grunt命令
- 内联样式不会被浏览器缓存,所以内联样式会被反复的加载
另外还有 Penthouse 和 criticalCSS 自动化工具也能达到相应的效果。待更新~
版权声明:本文标题:首屏渲染优化之critical css 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1726269366a1063631.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论