前端性能----静态资源,资源压缩

一、静态资源

  包括:html,CSS,js以外,还包括各种 图片资源、音频资源、字体资源等,由于有限的带宽和延迟影响,所以需要对资源做一些优化。

  注:都可对如上的静态资源进行压缩,且加缓存来实现

 

二、资源压缩

  概念:减小资源大小的过程叫做资源压缩。针对不同类型的资源有不同的压缩技术。本文主要总结文本资源的压缩。即我们网页上面的代码文本如JS、CSS等。

   注:压缩JS、CSS、image等前端资源(通常是由服务器来解决)

代码压缩

  代码文本里边有许多对于运行没有作用的部分,如多余的空白,注释,我们在生产环境中可以将它们去掉来减少网络传输字节。

gulp-uglify压缩JS

const gulp = require('gulp');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const gutil = require('gulp-util');

gulp.task('script', function() {
    gulp.src('src/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(uglify())
        .on('error', err=> {
             gutil.log(gutil.colors.red('[Error]'), err.toString()); 
        })
        .pipe(gulp.dest('dist'))
});

以src/script.js为例:

// script1
const a = 3;  //a

const b = 4;  // b

const c = 5;  // c

const arr1 = [a,b,c];

for(let item of arr1){  //遍历arr数组
    console.log(item);  //打印每一项
}

// 测试文件压缩方案。

// 测试修改

进行babel编译后,如果不压缩,大小为805字节,压缩后为468字节。gulp-uglify将所有代码压缩到一行,去除所有空格,注释。

 

sourcemap

源代码和编译后的代码或者是压缩后的代码差别比较大,也难以阅读,调试最终代码就变得很困难,可以使用sourcemap解决,还是以gulp为例,改写上面的gulpfile.js:

gulp.task('script', function() {
    gulp.src('src/*.js')
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(uglify())
        .on('error', err=> {
             gutil.log(gutil.colors.red('[Error]'), err.toString()); 
        })
        .pipe(sourcemaps.write('./maps'))
        .pipe(gulp.dest('dist'))
});

压缩css

  以gulp为例,gulp-minify-css会去除css中多余的空格、注释,还会将相同选择器的规则进行合并:

gulp.task('style',()=>{
    gulp.src('css/*.css')
        .pipe(minifyCSS())
        .pipe(gulp.dest('dist/css'))
});

压缩前:

html,body {
    width: 100%;
    height: 100%;
}
/*盒子相关*/
#red {
    width: 40px;
    height: 40px;
    background-color: red;
}
/*字体相关*/
#red {
    font-size: 16px;
    font-weight: bold;
}

压缩后:

body,html{width:100%;height:100%}#red{width:40px;height:40px;background-color:red;font-size:16px;font-weight:700}

Gzip

  gzip是很常用的Web资源压缩方案,以Node为例:

const gzip = require('zlib').createGzip();
const fs = require('fs');
const path = require('path');

const inp = fs.createReadStream(path.join(__dirname,'./file/test.txt')); //830字节
const outp = fs.createWriteStream(path.join(__dirname,'./file/test.txt.gzip')); //345字节

inp.pipe(gzip).pipe(outp); 

详细API见: https://nodejs.org/dist/latest-v8.x/docs/api/zlib.html

在express中使用Gzip压缩:

const compression = require('compression')
const express = require('express')

const app = express()
// compress all responses
app.use(compression())

HTTP压缩

首部字段

为了选择要采用的压缩算法,浏览器和服务器之间会使用主动协商机制。

客户端请求头:Accept-Encoding: xxx,xxx指明支持的压缩算法清单和优先级。

服务端�响应头:Content-Encoding: xxx指明使用的压缩算法。

原文地址:https://www.cnblogs.com/syw20170419/p/11938436.html