您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
pwa实现http请求缓存
发布时间:2020-06-06 10:51:23编辑:雪饮阅读()
本来呢,昨天就想给大家实现这个呢。无奈调试半天,又可能是因为这个pwa战线拉的太长了,自己的时间捉襟见肘,所以人一急起来,各种细节性的问题都难免忽略掉,导致一个细节而一直调试不成功。
调试技巧
首先由于pwa走缓存,这样你的代码是否生效很关键,所以在调试期间有个技巧
第一个就是随机数,这个如果有个几年经验的都不陌生了
其次就是这里,这里就是缓存,你要将他删除了
再然后就是卸载注册
http请求的缓存
我们在scr外面建立dev/service-worker.js,代码中重要的就是workbox全局变量,心急时在这里吃了亏,然后就是请求缓存处这里只给链接中包含getnewslist的请求进行缓存,因为我的目的是多个请求,然后仅仅给getnewslist缓存,以做对比。最后就是那个缓存策略,这里理所当然就设置为缓存优先咯。
// 引入workbox全局变量
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');
workbox.core.setCacheNameDetails({prefix: "pwa3"});
/**
* The workboxSW.precacheAndRoute() method efficiently caches and responds to
* requests for URLs in the manifest.
* See https://goo.gl/S9QRab
*/
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
// 动态ajax请求的缓存
workbox.routing.registerRoute(function(obj){
// console.log(obj); // {url: URL, event: FetchEvent}
// console.log(obj.url);
// 返回是否缓存结果
if (obj.url.pathname.includes('getnewslist')) {
return true;
} else {
return false;
}
// 缓存策略 缓存优先
},workbox.strategies.cacheFirst());
然后在src目录外建立vue.config.js如
module.exports = {
// ...other vue-cli plugin options...
pwa: {
name: 'My App',
themeColor: '#4DBA87',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
// configure the workbox plugin
workboxPluginMode: 'InjectManifest',
workboxOptions: {
// swSrc is required in InjectManifest mode.
swSrc: 'dev/service-worker.js',
// ...other Workbox options...
}
}
}
然后src/main.js中引入axios
import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import Axios from "axios"
Vue.prototype.$axios=Axios
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
然后src/app.vue中页面一加载我们就创建两个请求,一个就是上面我们允许缓存的请求,另外一个随便都可以
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
},
created() {
this.$axios.get('http://vue.gaojiupan.cn/api/getthumimages/0').
then(res=>{
console.log(res);
});
this.$axios.get('http://vue.gaojiupan.cn/api/getnewslist').
then(res=>{
console.log(res);
})
},
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
最后一步当然就是npm install axios安装axios和npm run build生产代码
http请求缓存体验
生产代码后将生产出来的代码拷贝到你的localhost环境中首次访问很正常
那么当你第二次刷新时会发现getnewslist接口是直接读取缓存的
那么离线状态下,该接口照样是200
关键字词:pwa,http,ajax,axios,请求,缓存
上一篇:vue-pwa实现
下一篇:pwa的https与离线app