网页加入自动更新

111 阅读1分钟

场景: 当前端部署项目后,需要提醒用户有去重新加载页面。

  1. 使用websocket去通知客户端更新,但是为了小功能加入websocket是没有必要。
  2. 去轮询请求index.html文件,从中解析里面的js文件,由于vue打包后每个js文件都有指纹标识,然后做对比即可。

根据第二个思路,采用json文件去做监听,这样体积小点。

version.json

{
    "version": "0.0.1"
}

autoUpdate.js

let lastVersion; //上一次获取到的版本号
let needTip = true; // 默认开启提示

async function extractNewVersion() {
	const json = await fetch('/static/version.json?timestamp=' + new Date().valueOf()).then((resp) => resp.json());
	localStorage.setItem('version', json.version)
	return json.version
}

async function needUpdate() {
	const newVersion = await extractNewVersion();
	console.log('new str', newVersion)
	if (!lastVersion) {
		lastVersion = newVersion;
		return false;
	}
	let result = false;
	if (lastVersion !== newVersion) {
		result = true;
	}
	lastVersion = newVersion;
	return result;
}
const DURATION = 5000;

function autoRefresh() {
	setTimeout(async () => {
		const willUpdate = await needUpdate();
		if (willUpdate) {
			const result = confirm("页面有更新,请刷新查看");
			if (result) {
				location.reload();
			}
			needTip = false; // 关闭更新提示,防止重复提醒
		}
		if (needTip) {
			autoRefresh();
		}
	}, DURATION)
}

extractNewVersion()
autoRefresh();

index.html加入脚本文件

    <script src="<%= BASE_URL %>static/autoUpdate.js"></script>