前端项目遇到的问题

每次前端项目在本地开发没事,一旦发布到线上就需要用户手动清理浏览器缓存,让用户总是吐槽,百度搜了很多文章都没找到解决方案,最终在钉钉源码中找到了解决方案。话不多说,直接上图:

1、判断Service Worker是否被安装

以谷歌浏览器为例:打开浏览器-开发者模式,进入Network,选择Doc


看到Status Code后面有 (from service worker)说明ServiceWorker没有被卸载。

2、卸载Service-Worker

话不多说,开始卸载:

2.1找到前端项目的src文件夹

2.2 src目录下添加serviceWorker.js,代码如下:

// This optional code is used to register a service worker.
// register() is not called by default.// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWAconst isLocalhost = Boolean(window.location.hostname === 'localhost' ||// [::1] is the IPv6 localhost address.window.location.hostname === '[::1]' ||// 127.0.0.0/8 are considered localhost for IPv4.window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);export function register(config) {if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {// The URL constructor is available in all browsers that support SW.const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);if (publicUrl.origin !== window.location.origin) {// Our service worker won't work if PUBLIC_URL is on a different origin// from what our page is served on. This might happen if a CDN is used to// serve assets; see https://github.com/facebook/create-react-app/issues/2374return;}window.addEventListener('load', () => {const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;if (isLocalhost) {// This is running on localhost. Let's check if a service worker still exists or not.checkValidServiceWorker(swUrl, config);// Add some additional logging to localhost, pointing developers to the// service worker/PWA documentation.navigator.serviceWorker.ready.then(() => {console.log('This web app is being served cache-first by a service ' +'worker. To learn more, visit https://bit.ly/CRA-PWA');});} else {// Is not localhost. Just register service workerregisterValidSW(swUrl, config);}});}
}function registerValidSW(swUrl, config) {navigator.serviceWorker.register(swUrl).then(registration => {registration.onupdatefound = () => {const installingWorker = registration.installing;if (installingWorker == null) {return;}installingWorker.onstatechange = () => {if (installingWorker.state === 'installed') {if (navigator.serviceWorker.controller) {// At this point, the updated precached content has been fetched,// but the previous service worker will still serve the older// content until all client tabs are closed.console.log('New content is available and will be used when all ' +'tabs for this page are closed. See https://bit.ly/CRA-PWA.');// Execute callbackif (config && config.onUpdate) {config.onUpdate(registration);}} else {// At this point, everything has been precached.// It's the perfect time to display a// "Content is cached for offline use." message.console.log('Content is cached for offline use.');// Execute callbackif (config && config.onSuccess) {config.onSuccess(registration);}}}};};}).catch(error => {console.error('Error during service worker registration:', error);});
}function checkValidServiceWorker(swUrl, config) {// Check if the service worker can be found. If it can't reload the page.fetch(swUrl, {headers: { 'Service-Worker': 'script' }}).then(response => {// Ensure service worker exists, and that we really are getting a JS file.const contentType = response.headers.get('content-type');if (response.status === 404 ||(contentType != null && contentType.indexOf('javascript') === -1)) {// No service worker found. Probably a different app. Reload the page.navigator.serviceWorker.ready.then(registration => {registration.unregister().then(() => {window.location.reload();});});} else {// Service worker found. Proceed as normal.registerValidSW(swUrl, config);}}).catch(() => {console.log('No internet connection found. App is running in offline mode.');});
}
//核心代码在这里,其他的都可以不要
export function unregister() {if ('serviceWorker' in navigator) {navigator.serviceWorker.ready.then(registration => {registration.unregister();});}
}

2.3 src目录下添加index.js(已有的可以不用创建,添加核心代码),代码如下:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';ReactDOM.render(<App />, document.getElementById('root'));// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
//核心代码在这里,其他的都可以不要
serviceWorker.unregister();

2.4 打包部署项目,再次打开页面,查看Service Worker是否被安装


发现ServiceWork已消失。

总结

需要在前端项目里添加如下核心代码:
serviceWorker.js

export function unregister() {if ('serviceWorker' in navigator) {navigator.serviceWorker.ready.then(registration => {registration.unregister();});}
}

index.js

import React from 'react';
import './index.css';
import * as serviceWorker from './serviceWorker';
serviceWorker.unregister();

注:

我从钉钉开发平台的前端项目源码中找到的解决方案,钉钉项目是H5微应用,我的项目是用React写的,框架不一样但是原理相通。
钉钉微应用源码:钉钉H5微应用前端项目开发Demo
可执行以下命令,下载前端代码。

git clone https://github.com/opendingtalk/eapp-corp-project-fe

另外,也可以尝试在Nginx的配置文件的location中添加如下代码:

    location / {# proxy_no_cache 1 add_header Cache-Control "no-cache";try_files $uri $uri/ /index.html;}

React、Vue等前端项目彻底卸载ServiceWorker,亲测有效相关推荐

  1. Vue下载安装步骤的详细教程(亲测有效) 2 安装与创建默认项目

    上篇请移步到Vue下载安装步骤的详细教程(亲测有效) 1_水w的博客-CSDN博客 上一篇博文已经对Node.js的安装与配置进行了详细介绍. 另外:文中项目存放的路径及项目名称可根据自身实际情况进行 ...

  2. 百度下mysql卸载_如何把Mysql卸载干净(亲测有效)

    如何完美的卸载掉mysql?按以下几个步骤去执行. 步骤一 确认你的mysql服务是关闭的状态,不然卸载不干净. 在我的电脑(计算机)-- 管理 – 服务和应用程序 – 服务,找到mysql 把状态关 ...

  3. SQL Server 2008完全卸载(亲测有效)

           因为下载了一个高版本的数据库,本来想将SQL Server 2008升级到SQL Server 2008 R2,但是屡次升级失败,就将它卸载干净,直接安装SQL Server 2008 ...

  4. Idea搭建VUE+elementUi前端项目

    1.首先打开idea选择 javascript 2.项目web项目搭建成功 3.先输入vue in it webpack,路由之前全部回车,包括路由!路由之后全部选n回车!最后一个选npm就行了,就让 ...

  5. Vue下载安装步骤的详细教程(亲测有效) 1

    目录 一.[准备工作]nodejs下载安装(npm环境) 1 下载安装nodejs 2 查看环境变量是否添加成功 3.验证是否安装成功 4.修改模块下载位置 (1)查看npm默认存放位置 (2)在 n ...

  6. SQL 2008 R2卸载(亲测有用)

    文章目录 一.卸载SQL Server 2008 (R2) 1.找到控制面板,win8及win7都可以直接点解"开始"按钮找到. 2.点击程序分类下的"卸载程序" ...

  7. Android开发之修改项目的仓库地址亲测有效

    很简单: 直接找到你项目git文件夹下面的config文件里面的url即可:如下图: 第一步: 第二步: 第三步: 修改里面的url仓库地址: 再介绍一种最简单的修改办法:Windows和Mac通用 ...

  8. vue中禁止ios橡皮筋效果(亲测有效)

    相信有很多前端的朋友都遇到过这个问题,这个问题真的很头疼.ios的橡皮筋效果会带来一些莫名其妙的bug.如果直接对body禁止的话,那整个页面都无法滑动了.所以我今天带来一个解决方案.原博客找不到了, ...

  9. 2021年新版电影小程序商业版+前端无后门+搭建教程亲测可用

    介绍: 2021年新版电影小程序商业版+前端 – 持续更新 无后门 网盘下载地址: http://kekewl.org/p2MNivrlgjz 图片:

最新文章

  1. Noip前的大抱佛脚----字符串
  2. kettle的安装与连接mysql(包含mysql8)简单使用,
  3. oracle的cursor的介绍
  4. OpenGL无边界的纹理实例
  5. c语言实现结构体变量private,C语言中结构体变量私有化详解
  6. K均值聚类关于初始聚类中心的探讨(matlab程序)
  7. 港大计算机科学奖学金,香港大学奖学金情况怎么样?
  8. 【Vue】样式穿透 ::v-deep的具体使用
  9. 双显卡单独分辨率_显卡预算超低、除了二手,你还可以考虑它、肥猫RX560显卡 评测...
  10. Activiti 6.0 概述与 Hello World 快速入门 与 核心 API 概述
  11. java tcp socket 关闭_JAVA SOCKET和TCP四次挥手
  12. Linux 开源词典工具及下载链接
  13. 转载:机器人工程师学习计划(YY硕)
  14. 《插件积累》页面音乐下载,付费音乐下载.
  15. 15款替代微软产品的开源软件
  16. Photoshop DPI缩放比例问题
  17. 《马克思主义基本原理》复习整理
  18. 交换机ftp将文件传到服务器,如何用FTP实现交换机间配置文件复制?
  19. zoom如何使用网页版登录
  20. java租车_Java 哒哒租车系统(控制台)

热门文章

  1. HTML5+CSS3之快速入门 day6-day10布局,表单,css精灵,css hack,BFC规范
  2. ThinkPHP5.0+PHPMailer 实现qq邮箱验证码
  3. Hyper-v安装和使用
  4. Excel VBA 批量取工作表名称
  5. 考初级计算机证需要考什么,计算机初级证书要考哪些内容
  6. PVZ系列六 | 僵尸动画转换
  7. 电脑网络正常,浏览器连不上网的解决办法
  8. 7.27 web前端-淘宝首页设计3
  9. ant弹窗_基于AntDesign改造优化的Modal弹窗
  10. 01.使用.svg格式图片生成app图标详细步骤和注意事项