Skip to content

Instantly share code, notes, and snippets.

@ravenclaw900
Created April 26, 2025 19:12
Show Gist options
  • Save ravenclaw900/031fc38dd7069ca97bb2895aafb0c1b4 to your computer and use it in GitHub Desktop.
Save ravenclaw900/031fc38dd7069ca97bb2895aafb0c1b4 to your computer and use it in GitHub Desktop.
A bigskysoftware/fixi-like web component
class ServerSwap extends HTMLElement {
connectedCallback() {
const url = this.getAttribute("action") || window.location.href;
const method = (this.getAttribute("method") || "GET").toUpperCase();
const trigger = this.getAttribute("trigger") || "click";
const targetAttr = this.getAttribute("target");
const target = !targetAttr ? this : targetAttr == "none" ? null : document.querySelector(targetAttr);
const swap = async () => {
try {
const resp = await fetch(url, { method, headers: { "fx-request": "true" } });
const text = await resp.text();
if (!resp.ok)
throw new Error(`${resp.statusText}: ${text}`);
if (target)
target.outerHTML = text;
} catch (err) {
document.querySelector("main").innerHTML = `Error: ${err.message}`;
}
};
if (trigger == "poll")
setTimeout(swap, 2000);
else
this.addEventListener(trigger, swap);
}
}
customElements.define("server-swap", ServerSwap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment