Created
April 26, 2025 19:12
-
-
Save ravenclaw900/031fc38dd7069ca97bb2895aafb0c1b4 to your computer and use it in GitHub Desktop.
A bigskysoftware/fixi-like web component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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