阿里云主机折上折
  • 微信号
Current Site:Index > Enable Gzip/Brotli compression technology

Enable Gzip/Brotli compression technology

Author:Chuan Chen 阅读数:19248人阅读 分类: 性能优化

Enable Gzip/Brotli Compression Technology

In modern web applications, the size of resource files directly impacts page loading speed. Gzip and Brotli, as two mainstream compression algorithms, can significantly reduce the transmission size of text-based resources. By properly configuring server compression strategies, a compression rate of 50%-70% can typically be achieved, which directly improves first-screen loading speed.

In-Depth Analysis of Compression Technology Principles

Gzip is based on the DEFLATE algorithm, combining the LZ77 algorithm with Huffman coding. When the server detects that the client supports Gzip, it compresses the response body and adds Content-Encoding: gzip to the response headers. The typical compression process includes:

  1. Finding repeated strings and replacing them with pointers
  2. Using dynamic Huffman coding to reduce the bit representation of characters
  3. Outputting the compressed bitstream

Brotli, a newer algorithm developed by Google, uses a variant of LZ77 and second-order context modeling. Compared to Gzip, Brotli's dictionary contains over 13,000 common string patterns from web resources, making it more efficient at compressing HTML/CSS/JS files. Brotli's compression level ranges from 0 to 11, while Gzip ranges from 1 to 9.

Server Configuration in Practice

Enabling Dual Compression in Nginx

http {
  gzip on;
  gzip_types text/plain text/css application/json application/javascript;
  gzip_min_length 256;
  gzip_comp_level 6;

  brotli on;
  brotli_types text/plain text/css application/json application/javascript;
  brotli_comp_level 6;
  brotli_static on;
}

Key parameter explanations:

  • gzip_min_length: Files smaller than this value will not be compressed
  • brotli_static: Prioritizes sending pre-compressed .br files
  • Recommended compression level: 4-6 (higher levels consume more CPU with diminishing returns)

Node.js Middleware Configuration

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

// Prioritize Brotli, fall back to Gzip
app.use(compression({
  filter: shouldCompress,
  threshold: 0,
  brotli: {
    quality: 5
  }
}))

function shouldCompress(req, res) {
  // Exclude already compressed binary files
  if (req.headers['x-no-compression']) return false
  return compression.filter(req, res)
}

Frontend Build Optimization Integration

Webpack plugins for generating pre-compressed files:

const CompressionPlugin = require('compression-webpack-plugin')
const BrotliPlugin = require('brotli-webpack-plugin')

module.exports = {
  plugins: [
    new CompressionPlugin({
      filename: '[path][base].gz',
      algorithm: 'gzip',
      test: /\.(js|css|html|svg)$/,
      threshold: 10240,
      minRatio: 0.8
    }),
    new BrotliPlugin({
      asset: '[path].br',
      test: /\.(js|css|html|svg)$/,
      quality: 11
    })
  ]
}

After building, the following files will be generated:

  • original.js
  • original.js.gz
  • original.js.br

Cache Strategy and Content Negotiation

Properly handle cache headers to avoid repeated compression:

HTTP/1.1 200 OK
Content-Type: text/javascript
Content-Encoding: br
Vary: Accept-Encoding
Cache-Control: public, max-age=31536000

Key points:

  • Vary: Accept-Encoding ensures different versions are cached for different clients
  • CDN must support passing the Accept-Encoding header
  • Pre-compressed files should have longer cache times

Performance Comparison Test Data

WebPageTest results for a typical SPA application:

Compression Resource Size Transfer Size CPU Time
No Compression 2.1MB 2.1MB 0ms
Gzip 2.1MB 543KB 23ms
Brotli 2.1MB 498KB 45ms

Mobile network environment (Slow 3G):

  • No compression: 8.7s load time
  • Gzip: 3.2s load time
  • Brotli: 2.9s load time

Handling Edge Cases

Fallback mechanisms when clients lack support:

// Check Accept-Encoding header
const acceptsEncoding = req.headers['accept-encoding']
const supportsGzip = acceptsEncoding.includes('gzip')
const supportsBrotli = acceptsEncoding.includes('br')

// Server-side selection logic
if (supportsBrotli && hasBrotliPrecompressed) {
  sendBr()
} else if (supportsGzip) {
  sendGzip()
} else {
  sendRaw()
}

Common troubleshooting steps:

  1. Check Nginx error logs for brotli module status
  2. Ensure correct MIME types (e.g., application/wasm should not be compressed)
  3. For dynamic content, use chunked encoding compression

Advanced Tuning Techniques

Optimizations for specific content types:

  1. JSON API Responses:

    • Enable dictionary training (Brotli-specific)
    • Set Content-Type: application/json+br
  2. SVG Images:

    gzip_types image/svg+xml;
    brotli_types image/svg+xml;
    
  3. WebAssembly:

    • Disable compression for .wasm files
    • Add wasm-unsafe-eval CSP policy
  4. Dynamic Content Compression:

    gzip_proxied any;
    gzip_disable "msie6";
    

Browser Support Status

Progressive enhancement via feature detection:

// Detect Brotli support
const brotliSupported = () => {
  const headers = new Headers()
  headers.append('Accept-Encoding', 'br')
  return fetch('/test.txt', { headers })
    .then(res => res.headers.get('content-encoding') === 'br')
}

Browser support overview:

  • Brotli: Chrome 49+, Firefox 44+, Edge 15+
  • Gzip: All modern browsers
  • IE11 only supports Gzip with some known bugs

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.