Skip to content

Instantly share code, notes, and snippets.

@ryrun
Last active March 3, 2020 10:15
Show Gist options
  • Save ryrun/94da7ad3ecfa66c623fca4364a4219e6 to your computer and use it in GitHub Desktop.
Save ryrun/94da7ad3ecfa66c623fca4364a4219e6 to your computer and use it in GitHub Desktop.
Simple auto reload page on change, Live edit / Live preview
//pretty dirty autoreload script
var lastMod = [];
var files = [window.location.href];
var countReq = 0;
var hidden = false;
function __autoreload() {
var checkfiles = true;
if (document.hasFocus()) {
checkfiles = false;
hidden = false;
} else if (typeof document.hidden !== "undefined" && document.hidden === true) {
checkfiles = false;
hidden = true;
} else if (typeof document.msHidden !== "undefined" && document.msHidden === true) {
checkfiles = false;
hidden = true;
} else if (typeof document.webkitHidden !== "undefined" && document.webkitHidden === true) {
checkfiles = false;
hidden = true;
}
if (checkfiles) {
hidden = false;
countReq++;
files.forEach(function (url, i) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url);
xhr.onload = function () {
if (xhr.status === 200) {
var d = new Date(xhr.getResponseHeader("Last-Modified"));
if (typeof lastMod[i] !== "undefined") {
if (d.toString() !== lastMod[i].toString()) {
location.reload();
}
} else {
lastMod[i] = d;
}
}
};
xhr.send();
});
} else if (hidden && countReq > 10) {
location.reload();
}
setTimeout('__autoreload()', countReq > 10 ? 1000 : 250);
}
window.addEventListener('DOMContentLoaded', function () {
// add stylesheet
for (let file of document.styleSheets) {
if (typeof file !== "undefined" && file.href.indexOf(window.location.protocol + '//' + window.location.hostname) !== -1) {
files.push(file.href);
}
}
//add scrtipts files
for (let file of document.scripts) {
if (typeof file !== "undefined" && file.src.indexOf(window.location.protocol + '//' + window.location.hostname) !== -1) {
files.push(file.src);
}
}
__autoreload();
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment