Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Created October 31, 2023 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazy4groovy/5598ec30e07be3d6da9d8d895230f40e to your computer and use it in GitHub Desktop.
Save crazy4groovy/5598ec30e07be3d6da9d8d895230f40e to your computer and use it in GitHub Desktop.
client side script that detects deployment changes, callback (JavaScript)
export default function detectDeployment(
onDeployDetected: () => void,
timeoutSec = 60 * 60 // default 1 hour
) {
const scriptFiles = { cache: "" }; // as object for pointer reference
const profit$ = () =>
handleDetectScriptFileChanges(onDeployDetected, scriptFiles);
setInterval(profit$, timeoutSec * 1000);
profit$();
}
async function handleDetectScriptFileChanges(
onDeployDetected: () => void,
scriptFiles: { cache: string }
) {
let html = "";
try {
const response = await fetch(window.location.origin);
if (!response.ok) {
throw new Error("Network response was not OK");
}
html = await response.text();
} catch (error) {
console.error("Deployment detection error:", (error as Error).message);
return;
}
const currentScriptFiles = parseScriptFiles(html).sort().join(";");
if (!scriptFiles.cache) {
scriptFiles.cache = currentScriptFiles;
} else if (scriptFiles.cache !== currentScriptFiles) {
// If script file changes detected, then new deployment detected
onDeployDetected();
}
}
function parseScriptFiles(html: string): string[] {
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
return Array.from(doc.querySelectorAll("script"))
.map((script) => script.src)
.filter(Boolean);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment