spa界面自动更新

当用户页面在放置状态,我们的站点有刷新,这时候用户点击按钮或者跳转会出现报错的情况。其实这个是否需要用户去刷新界面加载最新的资源。so 下面是来自 袁老师 的思路

例如utils里面增加 autoUpdate.ts

let lastSrcs: Array<string | undefined>; //上一次获取到的script地址

const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm; // 匹配初次加载的html中script内容

// 执行获取所有script
async function extractNewScripts() {
	const html = await fetch('/?_timestamp=' + Date.now())
		.then((resp) => resp.text())

	scriptReg.lastIndex = 0;
	let result = [];
	let match;
	while ((match = scriptReg.exec(html))) {
		result.push(match.groups?.src)
	}
	return result
}

// 判断是否需要更新
async function needUpdate() {
	const newScripts = await extractNewScripts()
	if (!lastSrcs) { //初次不需要更新
		lastSrcs = newScripts
		return false
	}
	let result = false
	if (lastSrcs.length !== newScripts.length) { // js文件集合不同了需要更新
		result = true
	}
	for (let i = 0; i < lastSrcs.length; i++) { // 依次匹配script是否相同
		const element = lastSrcs[i];
		if (element !== newScripts[i]) {
			result = true
			break;
		}
	}
	lastSrcs = newScripts
	return result
}

const DURATION = 2000 // 默认检测的时间
function autoRefresh() { // 自动更新开启
	setTimeout(async() => {
		const willUpdate = await needUpdate()
		if (willUpdate) {
			const result = confirm('页面有更新,点击确定刷新页面')
			if (result) {
				location.reload()
			}
		}
		autoRefresh()
	}, DURATION);
}

autoRefresh()

然后在main 文件中引入即可

import '@/utils/autoUpdate';

以上是自动刷新的解决方案, 因为html中加载的内容是静态的内容不多,还有就是settime的时间是2秒性能完全不是问题的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值