Skip to content

Instantly share code, notes, and snippets.

@edofic
Created May 6, 2023 19:06
Show Gist options
  • Save edofic/5fdaeb1fd2e4f449c56426cc1ef9e604 to your computer and use it in GitHub Desktop.
Save edofic/5fdaeb1fd2e4f449c56426cc1ef9e604 to your computer and use it in GitHub Desktop.
htmx with a "backend" in service worker
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
<script src="https://unpkg.com/[email protected]"></script>
</head>
<body>
<h1>Hello</h1>
<button hx-get="/ui/button" hx-swap="afterend">Load</button>
<script>
// Install a service worker that intercepts requests to /ui/*
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("/sw.js")
.then((registration) => {
console.log("Service worker registered:", registration);
})
.catch((error) => {
console.error("Error registering service worker:", error);
});
}
</script>
</body>
</html>
// Respond with "hello from the other side" for requests to /ui/*
self.addEventListener("fetch", (event) => {
console.log("worker fetch", event)
const url = new URL(event.request.url);
if (url.pathname.startsWith("/ui/")) {
event.respondWith(new Response("hello from the other side"));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment