Skip to content

Instantly share code, notes, and snippets.

@rferreira
Created February 7, 2026 14:33
Show Gist options
  • Select an option

  • Save rferreira/f16085c82fcc2ea5e2189c02ead09882 to your computer and use it in GitHub Desktop.

Select an option

Save rferreira/f16085c82fcc2ea5e2189c02ead09882 to your computer and use it in GitHub Desktop.
reload-controller.js
import {Controller} from "@hotwired/stimulus";
/**
* Controller used during development to automatically reload the page when the server signals a change
*/
export default class ReloadController extends Controller {
// Store the abort controller as a class property
abortController = null;
timeoutId = null;
connect() {
this.schedule();
// Listen for turbo:click events
document.addEventListener("turbo:click", this.handleTurboClick.bind(this));
}
disconnect() {
// Clean up the event listener when the controller is disconnected
document.removeEventListener("turbo:click", this.handleTurboClick.bind(this));
this.cancelPendingRequests();
}
handleTurboClick() {
this.cancelPendingRequests();
}
cancelPendingRequests() {
// Cancel any pending fetch request
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
// Clear any scheduled check
if (this.timeoutId) {
clearTimeout(this.timeoutId);
this.timeoutId = null;
}
}
async check() {
console.warn("hot reload enabled for this page");
try {
this.abortController = new AbortController();
const response = await fetch("/reload", {
method: "HEAD",
signal: this.abortController.signal
});
if (response.status === 200) {
console.log("page changed:", response.status);
window.location.reload();
}
} catch (error) {
if (error.name !== "AbortError" || error.name !== "TypeError") {
console.warn("Error checking for page change:", error);
}
}
this.schedule();
}
schedule() {
const minDelay = 250;
const maxDelay = 1000;
const randomDelay = Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay;
this.timeoutId = setTimeout(() => this.check(), randomDelay);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment