In the front-end development application, performance has always been valued by everyone thing, but a judge application performance is to see the most intuitive page opens speed. A way in which to improve the response speed of the page is the page using the cache. A good caching strategy can shorten the distance page request resources, reduce latency, and since the cache file can be recycled can also reduce bandwidth and reduce network load.
Common front-end caching I will not describe here, the following enhanced its Storage-based, using the Map basically the same api.
I do not understand, please Ruan Yifeng science teacher when reading the following ECMAScript 6 Getting Started
Here is the basic code that will be enhanced on the basis of
class MinCache {
// 将数据存储在本地缓存中指定的 name 中
set (name, data) {
try {
uni.setStorageSync(name, data)
} catch (e) {
console.log(e)
}
}
// 从本地缓存中获取指定 name 对应的内容
get (name) {
let data
try {
data = uni.getStorageSync(name)
} catch (e) {
console.log(e)
}
return data
}
// 从本地缓存中移除指定 key
delete (name) {
try {
uni.removeStorageSync(name)
} catch (e) {
console.log(e)
}
}
// 返回一个布尔值,表示 name 是否在本地缓存之中
has (name) {
const value
try {
const res = uni.getStorageInfoSync()
value = res.keys.includes(name)
} catch (e) {
console.log(e)
}
return value
}
// 清理本地数据缓存
clear () {
try {
uni.clearStorageSync()
} catch (e) {
console.log(e)
}
}
}
export default MinCache复制代码
We know that the cache is often hazardous, then we are the best time to remove the specified data.
class CacheCell {
constructor (data, timeout) {
this.data = data
// 设置超时时间,单位秒
this.timeout = timeout
// 对象创建时候的时间
this.createTime = Date.now()
}
}复制代码
set (name, data, timeout = 1200) {
const cachecell = new CacheCell(data, timeout)
try {
uni.setStorageSync(name, cachecell)
} catch (e) {
console.log(e)
}
}
get (name) {
let data = null
try {
data = uni.getStorageSync(name)
if (!data) return null
const currentTime = Date.now()
const overTime = (currentTime - data.createTime) / 1000
if (overTime > data.timeout) {
try {
uni.removeStorageSync(name)
data = null
} catch (e) {
console.log(e)
}
}
} catch (e) {
console.log(e)
}
return data
}复制代码
Use the expiry time of the cache way, already meet most of the business scene.
Storage of uni-app different at different ends achieved:
H5 end to localStorage, browser 5M limit the size of the cache is the concept could be cleaned up
App plus.storage end of native, no size limitation is not caching, persistence
Each applet end its own storage api, data storage lifecycle consistent with the applet itself, that is over a certain time to clean up in addition to the user is automatically deleted or actively, otherwise the data have been available.
A single micro-channel applet key allowed maximum data length is stored in 1MB, all data stored in an upper limit of 10MB.
Alipay converted applet into a single data string of the maximum length of 200 * 1024. With a PayPal user, the same small caches the total ceiling of 10MB.
Baidu, headlines applet document to explain the size limit
In addition, H5 end also supports websql, indexedDB, sessionStorage; App end also supports SQLite , IO files and other local storage solutions.
We can see that in some end Storage is limited in size, in fact, we just want to cache data, not necessarily persist.
That use on the line in the application life cycle, but also directly manipulate Storage is not very good.
We know that there Map ES6 can do cache
The following code is based upon the encapsulated Map
let cacheMap = new Map()
let instance = null
let timeoutDefault = 1200
function isTimeout (name) {
const data = cacheMap.get(name)
if (!data) return true
if (data.timeout === 0) return false
const currentTime = Date.now()
const overTime = (currentTime - data.createTime) / 1000
if (overTime > data.timeout) {
cacheMap.delete(name)
return true
}
return false
}
class CacheCell {
constructor (data, timeout) {
this.data = data
this.timeout = timeout
this.createTime = Date.now()
}
}
class Cache {
set (name, data, timeout = timeoutDefault) {
const cachecell = new CacheCell(data, timeout)
return cacheMap.set(name, cachecell)
}
get (name) {
return isTimeout(name) ? null : cacheMap.get(name).data
}
delete (name) {
return cacheMap.delete(name)
}
has (name) {
return !isTimeout(name)
}
clear () {
return cacheMap.clear()
}
setTimeoutDefault (num) {
if (timeoutDefault === 1200) {
return timeoutDefault = num
}
throw Error('缓存器只能设置一次默认过期时间')
}
}
class ProxyCache {
constructor () {
return instance || (instance = new Cache())
}
}
export default ProxyCache复制代码
Map of Storage and packaging of integrated cache
Let's analyze
Storage Map and a common api
Resolve begin with an underscore _ named cache on the name to Storage, and also a copy of the Map
Try not to the Storage Operation (read slow)
It must be initialized when the application is loaded into the Storage Map
Like Vue plug-in to use
let cacheMap = new Map()
let timeoutDefault = 1200
function isTimeout (name) {
const data = cacheMap.get(name)
if (!data) return true
if (data.timeout === 0) return false
const currentTime = Date.now()
const overTime = (currentTime - data.createTime) / 1000
if (overTime > data.timeout) {
cacheMap.delete(name)
if (name.startsWith('_')) {
try {
uni.removeStorageSync(name)
} catch (e) {
console.log(e)
}
}
return true
}
return false
}
class CacheCell {
constructor (data, timeout) {
this.data = data
this.timeout = timeout
this.createTime = Date.now()
}
}
class MinCache {
constructor (timeout) {
try {
const res = uni.getStorageInfoSync()
res.keys.forEach(name => {
try {
const value = uni.getStorageSync(name)
cacheMap.set(name, value)
} catch (e) {
console.log(e)
}
})
} catch (e) {
console.log(e)
}
timeoutDefault = timeout
}
set (name, data, timeout = timeoutDefault) {
const cachecell = new CacheCell(data, timeout)
let cache = null
if (name.startsWith('_')) {
try {
uni.setStorageSync(name, cachecell)
cache = cacheMap.set(name, cachecell)
} catch (e) {
console.log(e)
}
} else {
cache = cacheMap.set(name, cachecell)
}
return cache
}
get (name) {
return isTimeout(name) ? null : cacheMap.get(name).data
}
delete (name) {
let value = false
if (name.startsWith('_')) {
try {
uni.removeStorageSync(name)
value = cacheMap.delete(name)
} catch (e) {
console.log(e)
}
} else {
value = cacheMap.delete(name)
}
return value
}
has (name) {
return !isTimeout(name)
}
clear () {
let value = false
try {
uni.clearStorageSync()
cacheMap.clear()
value = true
} catch (e) {
console.log(e)
}
return value
}
}
MinCache.install = function (Vue, {timeout = 1200} = {}) {
Vue.prototype.$cache = new MinCache(timeout)
}
export default MinCache复制代码
Instructions
name starts with an underscore _ named cache to Storage, and also a copy of the Map
Event name | parameter | Explanation | return value |
---|---|---|---|
set | name cache key, data cached data, timeout (unit number must s) buffer time default cache 1200s, timeout cache permanently set to 0 | Set cache data | Map collection |
get | name cache key | Get Data (cache expiration will return null) | Return the cached data DATA |
has | name cache key | Check the value | true/false |
delete | name cache key | delete data | true/false |
clear | - | Clear Storage cache data and Map | true/false |
// 注册缓存器
Vue.use(MinCache)
// 设置默认缓存时间
// Vue.use(MinCache, {timeout: 600})复制代码
// 'name'不是以下划线开头的表示会缓存到Map中,在程序生命周期内有并且在有效时间内有效
this.$cache.set('name', 'MinCache')
// 过期时间设置为0表示不会过期
// 注意:'test'并不是以下划线命名表示在程序生命周期永久缓存
this.$cache.set('test', 'testdemo', 0)
// 过期时间设置为0表示不会过期
// 注意:'_imgURL'是以下划线命名表示永久缓存到Storage
this.$cache.set('_imgURL', 'data', 0)复制代码
// 获取缓存的数据
this.imgURL = this.$cache.get('_imgURL')
this.name = this.$cache.get('name')
this.test = this.$cache.get('test')复制代码
You can refer to the specific use github
uni-app routing encapsulation
Reproduced in: https: //juejin.im/post/5d08a5c2f265da1bb003c0f8