當(dāng)我們打開一個(gè)網(wǎng)頁的時(shí)候,它回去查詢?yōu)g覽器緩存,看是否有要請(qǐng)求的文件,如果儲(chǔ)存,就會(huì)返回緩存的文件。如果不存在,才會(huì)請(qǐng)求服務(wù)器。
這就是 瀏覽器緩存
瀏覽器緩存是一種在本地保存資源的副本,他的大小是有限制的。當(dāng)我們請(qǐng)求過多的時(shí)候,繼續(xù)請(qǐng)求就需要緩存去確定哪些數(shù)據(jù)應(yīng)該被保留,哪些數(shù)據(jù)應(yīng)該被刪除。
這就是 瀏覽器緩存淘汰策略
常見的瀏覽器淘汰策略有以下幾種
- 先進(jìn)先出(FIFO)
- 最少使用(LFU)
- 最近最少使用(LRU)
JS實(shí)現(xiàn)FIFO
class FIFOCache {
constructor(limit) {
this.limit = limit || [];
this.map = {};
this.keys = [];
}
set(key, value) {
let map = this.map;
let keys = this.keys;
if (!Object.prototype.hasOwnProperty.call(map, key)) {
if (keys.length === this.limit) {
delete map[keys.shift()];
}
keys.push(key);
}
map[key] = value;
}
get(key) {
return this.map[key];
}
}
JS實(shí)現(xiàn)LRU
vue的keep-alive就是使用的LRU
class LRUCache {
constructor(limit) {
this.cache = new Map();
this.limit = limit;
}
put(key, value) {
if (this.cache.has(key)) {
this.cache.delete(key);
} else if (this.cache.size >= this.limit) {
this.cache.delete(this.cache.keys().next().value);
}
this.cache.set(key, value);
}
get(key) {
if (this.cache.has(key)) {
let temp = this.cache.get(key);
this.cache.delete(key);
this.cache.set(key, temp);
return temp;
}
return -1;
}
}