前端性能----靜態資源,資源壓縮

1、靜態資源

  包括:html,CSS,js之外,還包括各類 圖片資源、音頻資源、字體資源等,因爲有限的帶寬和延遲影響,因此須要對資源作一些優化。css

  注:均可對如上的靜態資源進行壓縮,且加緩存來實現html

 

2、資源壓縮

  概念:減少資源大小的過程叫作資源壓縮。針對不一樣類型的資源有不一樣的壓縮技術。本文主要總結文本資源的壓縮。即咱們網頁上面的代碼文本如JS、CSS等。前端

   注:壓縮JS、CSS、image等前端資源(一般是由服務器來解決)node

代碼壓縮

  代碼文本里邊有許多對於運行沒有做用的部分,如多餘的空白,註釋,咱們在生產環境中能夠將它們去掉來減小網絡傳輸字節。git

 

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爲例:github

// 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將全部代碼壓縮到一行,去除全部空格,註釋。web

 

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中多餘的空格、註釋,還會將相同選擇器的規則進行合併:express

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

壓縮前:gulp

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指明使用的壓縮算法。

相關文章
相關標籤/搜索