Skip to content

Instantly share code, notes, and snippets.

@RhinoLu
Created May 1, 2018 08:03
Show Gist options
  • Save RhinoLu/0bd23b14af8e8fcd3cf15bf6700072fb to your computer and use it in GitHub Desktop.
Save RhinoLu/0bd23b14af8e8fcd3cf15bf6700072fb to your computer and use it in GitHub Desktop.
check html version with meta content / 以 meta 檢查 html 版本
// 可搭配 pug 產生 version meta
// 例:<meta name="version" content="1589465168"> // content 可用 Date.now() 產生
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
function checkVersionMatch() {
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
// alert(httpRequest.responseText);
var parser = new DOMParser();
var doc = parser.parseFromString(httpRequest.responseText, "text/html");
// console.log(doc);
// console.log(getVersion(doc));
// console.log(getVersion(document));
if (getVersion(document) === "") {
// no meta
} else {
if (getVersion(document) !== getVersion(doc)) {
// version no match, reload html with some cache buster
location.search = location.search + "&_=" + Date.now();
} else {
// version match
}
}
} else {
// alert('There was a problem with the request.');
}
}
};
httpRequest.open('GET', location.origin + location.pathname + '?' + Date.now(), false);
httpRequest.send();
}
}
function getVersion(doc) {
var metas = doc.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
var attrs = metas[i].attributes;
for (var j = 0; j < attrs.length; j++) {
if (attrs[j].name && attrs[j].name === "version") {
return attrs[j].content;
}
}
}
return "";
}
@RhinoLu
Copy link
Author

RhinoLu commented May 1, 2018

建議搭配 cookie, 避免無限重刷...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment