1 概念和作用
顾名思义 是浏览器将数据暂时缓存在某一位置的方式;
作用:优化浏览器端用户体验的性能;缓存策略是在服务器端设置
通过浏览器缓存策略可以把从服务器请求的数据缓存在浏览器端;再次请求相同数据,不用发送http请求去服务器端获取数据,第一节省带宽,第二能提高用户体验。
对概念的消化必须建立在实际应用之上;杜绝似懂非懂。所以先用nodejs写几个接口进行测试,一睹为快,更有利于理解概念;
2 一睹为快:nodejs写restful缓存接口演示
2.1 新建一个api_cache.js
,然后在它的同目录执行 node api_cache.js即可(需要安装nodejs环境)
不需要安装别的包,全部使用nodejs内置包实现api 接口;下面代码,我们定义三个请求,一个返回js文件,一个返回图片,一个返回json数据。
// 协商缓存
const http = require('http')
const fs = require('fs')
var path = require('path');
let img = fs.readFileSync('./1.png');
http.createServer(function (request, response) {
// image
if (request.url === '/img/1') {
response.writeHead(200, {
'Content-Type': 'image/png',
});
response.end(img);
}
// script.js
if (request.url === '/script.js') {
response.writeHead(200, {
'Content-Type': 'text/javascript'
})
response.end("");
}
// 普通get请求
if (request.url === '/china') {
var file = path.join(__dirname, 'china.geojson');
fs.readFile(file, 'utf-8', function (err, data) {
response.writeHead(200,{
'Content-Type': 'application/json'
})
response.end(data);
})
}
}).listen(3000)
console.log("接口服务成功启动在3000接口");
启动接口如下:

2.2 新建一个test.html,调用我们的接口
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://localhost:3000/script.js"></script>
<script>
fetch('https://blog.csdn.net/service/http://localhost:3000/china').then(function(res){
console.log(res)
})
let img=new Image()
img.onload=function(){}
img.src="http://localhost:3000/img/1"
</script>
</head>
<body>
</body>
</html>
1.png.script.js和china.json,这三个文件可以自己新建,geojson数据可以在

本文介绍了浏览器缓存策略的概念和作用,通过Node.js编写RESTful缓存接口进行演示。详细讲解了强缓存和协商缓存,强缓存通过设置Expires和Cache-Control实现,协商缓存有Last-Modified与If-Modified-Since、Etag与If-None-Match两种机制,能优化性能、节省带宽。
1672

被折叠的 条评论
为什么被折叠?



