web开发中缓存优化

浏览器缓存

  • 强缓存

Expires (Expires:Thu, 30 Dec 2027 11:02:20 GMT)
Cache-Control (Cache-Control:max-age=315360000)

  • 协商缓存

If-Modified-Since / Last-Modified (Last-Modified:Wed, 22 Jun 2011 06:40:43 GMT)
If-None-Match / Etag (Etag:"2c1-4a6473f6030c0")

缓存实现流程

//配置缓存参数
cache: {
    maxAge: 600,
    expires: true,
    cacheControl: true,
    lastModified: true,
    etag: true
}
//定义缓存函数
const {cache} = require('../config/defaultConfig')

function refreshRes(stats,res) {
    if(cache.expires){
        res.setHeader('Expires',(new Date(Date.now() + cache.maxAge*1000)).toUTCString())
    }
    if(cache.cacheControl){
        res.setHeader('Cache-Control',`public,max-age=${cache.maxAge}`)

    }
    if(cache.lastModified){
        res.setHeader('Last-Modified',stats.mtime.toUTCString())
    }
    if(cache.etag){
        res.setHeader('ETag',`${stats.size}-${stats.mtime}`)
    }

}

module.exports = function (stats,req,res) {

    refreshRes(stats,res)

    const lastModified = req.headers['if-modified-since']
    const etag = req.headers['if-none-match']

    if(!lastModified && !etag){
        return false
    }
    const aaa = res.getHeaders()['last-modified']
    if(lastModified && lastModified !== res.getHeaders()['last-modified']){
        return false
    }

    if(etag && etag !== res.getHeaders()['etag']){
        return false
    }

    return true

}
//判断是否使用缓存
const isUseCache = require('../handle/cache')
if(isUseCache(stats,req,res)){
    res.statusCode = 304
    res.end()
    return
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 网络特有的延迟以及数据传输的成本,制约互联网快速获取Web资源。为此,HTTP协议引入缓存以空间换时间,使浏览器缓...
    大头8086阅读 3,107评论 2 12
  • 针对浏览器的http缓存的分析也算是老生常谈了,每隔一段时间就会冒出一篇不错的文章,其原理也是各大公司面试时几乎必...
    全端玩法阅读 905评论 0 9
  • 本文内容大多参考《图解HTTP》一书 一. 认识代理服务器 所以讲缓存为什么要先扯代理服务器?别急,让我们看一下一...
    流光号船长阅读 1,989评论 0 10
  • 转载:浏览器缓存知识小结及应用 阅读目录 1. 浏览器缓存基本认识 2. 强缓存的原理 3. 强缓存的管理 4. ...
    meng_philip123阅读 1,100评论 4 18
  • 浏览器缓存,也就是客户端缓存,既是网页性能优化里面静态资源相关优化的一大利器,也是无数web开发人员在工作过程不可...
    单纯的土豆阅读 419评论 0 1