当前位置: 首页 > wzjs >正文

建企业版网站多久鼠标垫东莞网站建设

建企业版网站多久,鼠标垫东莞网站建设,网站开发一般用哪个浏览器,泉州市网站设计企业🤖 作者简介:水煮白菜王,一位资深前端劝退师 👻 👀 文章专栏: 前端专栏 ,记录一下平时在博客写作中,总结出的一些开发技巧和知识归纳总结✍。 感谢支持💕💕&a…

在这里插入图片描述

🤖 作者简介:水煮白菜王,一位资深前端劝退师 👻
👀 文章专栏: 前端专栏 ,记录一下平时在博客写作中,总结出的一些开发技巧和知识归纳总结✍。
感谢支持💕💕💕

目录

  • 一、应用场景
  • 二、实现原理
    • 2.1 核心检测逻辑
    • 2.2 实现优势
  • 三 、具体实现
    • 3.1 工程化封装
    • 3.2 关键方法解析
      • 脚本哈希获取:
      • 对比逻辑:
  • 四、全部代码🚀🚀🚀
    • 4.1 vue3
    • 4.2 vue2
  • 五、注意事项与常见问题
    • 5.1 可能出现的问题
    • 5.2 浏览器兼容方案

一、应用场景

在现代Web应用中,为了提升用户体验并确保系统的稳定性和一致性,部署前端版本更新后及时提醒用户进行页面刷新是至关重要的。当生产环境发布了包含功能变化的新版本时,由于单页面(SPA)应用的路由特性和浏览器缓存机制,用户浏览器可能不会自动加载最新的代码资源,这可能导致用户遇到bug或体验到不一致的功能行为。通过实现自动检测机制来提醒用户版本更新,并引导其刷新页面,可以

  1. 避免用户使用过期版本
  2. 确保功能一致性
  3. 减少接口兼容性问题
  4. 提高应用可靠性

二、实现原理

2.1 核心检测逻辑

变化
未变化
应用启动
生产环境?
启动定时器
结束流程
等待60秒
获取当前脚本哈希
首次运行?
保存初始哈希
哈希变化?
停止定时器
显示更新提示
用户确认?
刷新页面
记录取消操作

通过对比构建产物的哈希值变化实现版本检测:

  1. 定时轮询:每分钟检查静态资源变化
  2. 哈希对比:通过解析HTML中script标签指纹判断更新
  3. 强制刷新:检测到更新后提示用户刷新页面
// 核心对比逻辑
const isChanged = (oldSet, newSet) => {return oldSet.size !== newSet.size || ![...oldSet].every(hash => newSet.has(hash))
}

2.2 实现优势

  • 通用性强:适用于任意前端框架
  • 无侵入式检测:不依赖构建工具配置
  • 用户可控:提示框让用户选择刷新时机
  • 精准检测:通过对比script标签内容哈希值
  • 低资源消耗:每分钟检测一次,单次请求性能消耗低

三 、具体实现

3.1 工程化封装

// useVersionHash.js 核心实现
export default function useVersionHash() {// 状态管理const timerUpdate = ref(null)let scriptHashes = new Set()// 生命周期onMounted(() => startTimer())onBeforeUnmount(() => stopTimer())// 业务方法const fetchScriptHashes = async () => { /*...*/ }const compareScriptHashes = async () => { /*...*/ }return { compareScriptHashes }
}

3.2 关键方法解析

脚本哈希获取:

const fetchScriptHashes = async () => {const html = await fetch('/').then(res => res.text())const scriptRegex = /<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gireturn new Set(html?.match(scriptRegex) || [])
}

对比逻辑:

if (scriptHashes.size === 0) {// 初始化基准值scriptHashes = newScriptHashes  
} else if (scriptHashes.size !== newScriptHashes.size ||![...scriptHashes].every(hash => newScriptHashes.has(hash))
) {// 触发更新流程stopTimer()showUpdateDialog()
}

四、全部代码🚀🚀🚀

4.1 vue3

1、use-version-update.js具体逻辑

// @/utils/use-version-update.js
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessageBox } from 'element-plus'let scriptHashes = new Set()
const timerUpdate = ref(null)export default function useVersionHash() {const isProduction = import.meta.env.MODE === 'production'const fetchScriptHashes = async () => {try {const html = await fetch('/').then((res) => res.text())const scriptRegex = /<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gireturn new Set(html?.match(scriptRegex) || [])} catch (error) {console.error('获取脚本哈希失败:', error)return new Set()}}const compareScriptHashes = async () => {try {const newScriptHashes = await fetchScriptHashes()if (scriptHashes.size === 0) {scriptHashes = newScriptHashes} else if (scriptHashes.size !== newScriptHashes.size ||![...scriptHashes].every(hash => newScriptHashes.has(hash))) {stopTimer()updateNotice()}} catch (error) {console.error('版本检查失败:', error)}}const updateNotice = () => {ElMessageBox.confirm('检测到新版本,建议立即更新以确保平台正常使用','更新提示',{confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => window.location.reload())}const startTimer = () => {if (!isProduction) returntimerUpdate.value = setInterval(compareScriptHashes, 60000)}const stopTimer = () => {timerUpdate.value && clearInterval(timerUpdate.value)}onMounted(startTimer)onBeforeUnmount(stopTimer)return { compareScriptHashes, updateNotice }
}

2、引入use-version-update.js

// App.vue
import versionUpdatefrom '@/utils/use-version-update.js'
export default {setup() {const { updateNotice } = versionUpdate()return { updateNotice }}
}

3、Vite 相关配置

// vite.config.js
import { defineConfig } from 'vite'export default defineConfig({build: {rollupOptions: {output: {// 主入口文件命名规则entryFileNames: 'js/[name]-[hash:8].js',// 代码分割块命名规则chunkFileNames: 'js/[name]-[hash:8].js',// 静态资源文件命名规则assetFileNames: ({ name }) => {const ext = name?.split('.').pop()return `assets/${ext}/[name]-[hash:8].[ext]`}}},// 启用文件哈希的manifest生成manifest: true}
})

也可以将use-version-update写成以JS、TS模块化封装,在入口文件中main.ts引入

// use-version-update.ts
export const versionUpdate = () => {... 具体处理逻辑
}// main.ts
import { versionUpdate} from "@/utils/use-version-update"
if (import.meta.env.MODE == 'production') {versionUpdate()
}

4.2 vue2

1、use-version-update.js具体逻辑

/** @Author: baicaiKing* @Date: 2025-01-02 13:50:33* @LastEditors: Do not edit* @LastEditTime: 2025-01-03 09:40:36* @FilePath: \code\src\utils\use-version-update.js*/
// 存储当前脚本标签的哈希值集合
let scriptHashes = new Set();
let timerUpdate = undefined;
export default {data() {return {};},created() {},mounted() {// 每60秒检查一次是否有新的脚本标签更新if (process.env.NODE_ENV === 'production') { // 只针对生产环境timerUpdate= setInterval(() => {this.compareScriptHashes()}, 60000);}},beforeDestroy() {clearInterval(timerUpdate);timerUpdate = null;},methods: {/*** 从首页获取脚本标签的哈希值集合* @returns {Promise<Set<string>>} 返回包含脚本标签的哈希值的集合*/async fetchScriptHashes() {// 获取首页HTML内容const html = await fetch('/').then((res) => res.text());// 正则表达式匹配所有<script>标签const scriptRegex = /<script(?:\s+[^>]*)?>(.*?)<\/script\s*>/gi;// 获取匹配到的所有<script>标签内容// const scripts = html.match(scriptRegex) ?? [];const scripts = html ? html.match(scriptRegex) || [] : [];// 将脚本标签内容存入集合并返回return new Set(scripts);},/*** 比较当前脚本标签的哈希值集合与新获取的集合,检测是否有更新*/async compareScriptHashes() {// 获取新的脚本标签哈希值集合const newScriptHashes = await this.fetchScriptHashes();if (scriptHashes.size === 0) {// 初次运行时,存储当前脚本标签哈希值scriptHashes = newScriptHashes;} else if (scriptHashes.size !== newScriptHashes.size ||![...scriptHashes].every((hash) => newScriptHashes.has(hash))) {// 如果脚本标签数量或内容发生变化,则认为有更新console.info('已检测到更新文件', {oldScript: [...scriptHashes],newScript: [...newScriptHashes],});// 清除定时器clearInterval(timerUpdate);// 提示用户更新this.updateNotice();} else {// 没有更新console.info('未检测到更新时机', {oldScript: [...scriptHashes],});}},updateNotice() {this.$confirm('检测到新版本,建议立即更新以确保平台正常使用', '更新提示', {confirmButtonText: '确定',cancelButtonText: '取消(自行刷新)',type: 'warning'}).then(() => {window.location.reload();}).catch(() => {console.eror('用户取消刷新!');});}},};

2、引入use-version-update.js

// App.vue
import versionUpdate from "@/util/use-version-update.js";
export default {name: "app",mixins: [versionUpdate],data() {return {};},
};

3、Webpack 相关配置


// vue.config
module.exports = {configureWebpack: {output: {filename: 'js/[name].[hash].js',// filename: 'js/[name].[contenthash].js',},},devServer: {},
};

五、注意事项与常见问题

5.1 可能出现的问题

问题现象可能原因解决方案
检测不准确正则匹配失效更新正则表达式
生产环境未生效环境变量配置错误检查构建配置
跨域请求失败部署路径不匹配调整fetch请求路径
内存泄漏定时器未正确清除使用WeakRef优化

5.2 浏览器兼容方案

可结合Service Worker实现无缝更新

// 支持Service Worker的渐进增强方案
if ('serviceWorker' in navigator) {navigator.serviceWorker.register('/sw.js').then(reg => {reg.addEventListener('updatefound', () => {showUpdateNotification()})})
}

同时要确保服务器配置正确缓存策略,通常Nginx缓存策略默认不用打理

在这里插入图片描述
如果你觉得这篇文章对你有帮助,请点赞 👍、收藏 👏 并关注我!👀
在这里插入图片描述


文章转载自:

http://J9Q9AlVG.gtgwh.cn
http://ivUysBq7.gtgwh.cn
http://b91gDCe9.gtgwh.cn
http://p55t5bQI.gtgwh.cn
http://lwa11HXf.gtgwh.cn
http://5cEL8d39.gtgwh.cn
http://nLQzlazh.gtgwh.cn
http://6P09gy2I.gtgwh.cn
http://yCdxhhPe.gtgwh.cn
http://jtyq2hjz.gtgwh.cn
http://02vSrV7Z.gtgwh.cn
http://ukiKy3qQ.gtgwh.cn
http://3ssIhX1N.gtgwh.cn
http://AWarIcG6.gtgwh.cn
http://IbFck8CX.gtgwh.cn
http://9eYOoewa.gtgwh.cn
http://kuXseLZC.gtgwh.cn
http://Y6DWIkQn.gtgwh.cn
http://9KzcwXYy.gtgwh.cn
http://D5nlv9F9.gtgwh.cn
http://NFy31QPB.gtgwh.cn
http://T6vGWOI9.gtgwh.cn
http://UjYaKcCw.gtgwh.cn
http://lWfYz579.gtgwh.cn
http://vwbHQrg0.gtgwh.cn
http://fKb7EEoZ.gtgwh.cn
http://4Eu51Lh3.gtgwh.cn
http://gEgHvt3q.gtgwh.cn
http://e50G2W2U.gtgwh.cn
http://kJyjdWsL.gtgwh.cn
http://www.dtcms.com/wzjs/756949.html

相关文章:

  • 360建站模板优化网站用软件好吗
  • 信用网站一体化建设方案工厂展厅设计效果图
  • 石家庄网站建设培训音乐分享网站源码
  • 诸城网站开发软文外链购买平台
  • 教育政务网站建设2015做那些网站能致富
  • wordpress建站有广告吗长葛网站建设公司
  • 南宁百度网站公司哪家好嘉兴网络项目建站公司
  • 静海网站建设公司廊坊seo网站排名
  • 网站首页导航怎么做二级导航平面设计师的工作内容
  • 网站备案导致网站被k在上海找工作用哪个招聘网好
  • 建立网站的方案网络营销有什么方式
  • 如何推广网站链接工程建设造价信息网站
  • 设计网站推荐国外iapp怎么把网站做软件
  • 深圳建设发展有限公司深圳网站关键字优化
  • 无为县住房和城乡建设局网站首页东莞能做网站的公司
  • 南昌网站建设公司网站建设公司哪家好营销活动网站
  • 荆州松滋网站建设自媒体怎么入门
  • 网站图片怎么做优化定制小程序制作一个需要多少钱
  • 网站域名管理怎么登陆深圳汇网网站建设
  • 免费网站服务器安全软件下载网页设计导航条怎么做
  • 四川网站建设套餐网站推广的基本方法是
  • 网站首页包含的内容eclipse视频网站开发
  • 天博网站建设网站的背景图怎么做
  • 特色设计网站推荐上海诚杰华建设工程咨询有限公司网站
  • 深圳微商城网站设计多少钱云梦网络建站
  • 太原网站建设开发公司全球最新数据消息
  • 知名门户网站go语言可以做网站吗
  • 微网站建设找哪家公司好不同网站建设特点
  • wordpress widget logicwordpress论坛优化
  • 网页制作与网站建设试题和答案wordpress保存帖子数据库