Skip to content

Instantly share code, notes, and snippets.

@fimion
Forked from mikeckennedy/server-hot-reload.js
Last active August 18, 2023 20:26
Show Gist options
  • Save fimion/d8f6f44362fe742f61e09aaee4fe42e1 to your computer and use it in GitHub Desktop.
Save fimion/d8f6f44362fe742f61e09aaee4fe42e1 to your computer and use it in GitHub Desktop.
Server-side hot reload checker by Michael Kennedy. When the contents of the page change in any way, the page will be reloaded.
// *************************************************************************
// Server-side hot reload check by Michael Kennedy (https://mkennedy.codes).
// Released under the MIT open source license, 2023.
//
// Usage: Include this file in your "application shell" layout template
// or directly into any page you'd like to check.
//
// Set the checkIntervalInMs time to the frequency you need. Usually 1 sec
// should be fine, but if a page is slow maybe increase the delay.
//
// When the contents of the page change in any way, the page will be reloaded.
//
let currentPageHash = "UNKNOWN";
let checkIntervalInMs = 1000;
let setIntervalInstance;
// *************************************************************************
// When the doc is ready, we'll start checking for changes.
//
document.addEventListener("DOMContentLoaded", function () {
console.log("Server hot reload active at " + new Date().toLocaleTimeString() + ". Watching for changes ...");
const url = document.location.href;
setIntervalInstance = setInterval(() => downloadHtml(url).then(reloadIfNecessary), checkIntervalInMs);
});
// *************************************************************************
// Called on every page content check (interval is checkIntervalInMs milliseconds).
//
function reloadIfNecessary(html) {
const newHash = hashCode(html);
if(!newHash) return;
if (currentPageHash === "UNKNOWN") {
// Compute the hash since have never seen this response on this URL before (first run).
currentPageHash = newHash;
return;
}
if (newHash === currentPageHash) {
return;
}
// Something, somewhere in the page has changed. Reload
console.log("Page change detected, reloading now!")
window.location.reload();
}
function hashcode (html) {
let hash = 0, i, chr;
if (html.length === 0) return hash;
for (i = 0; i < html.length; i++) {
chr = html.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
async function downloadHtml(url) {
const thisURL = new URL(url)
thisURL.searchParams.append('server_hot_reload_check=true')
try{
const request = await fetch(thisURL);
return request.text();
} catch (e) {
console.log("Something went wrong. Stopping hot reload.")
clearInterval(setIntervalInstance);
return '';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment