Skip to content

Instantly share code, notes, and snippets.

@jon49
Last active October 19, 2025 07:12
Show Gist options
  • Select an option

  • Save jon49/b341c43903e270808da0d06e3e268a90 to your computer and use it in GitHub Desktop.

Select an option

Save jon49/b341c43903e270808da0d06e3e268a90 to your computer and use it in GitHub Desktop.
htmz implementation with the back end driving the targets/swapping methods.
window.htmz = function htmz(frame) {
let location = frame.contentWindow?.location
if (location == null || location.href === "about:blank") return;
let doc = frame.contentDocument
if (doc == null) return
for (let el of Array.from(doc.body.children).concat(Array.from(doc.head.children))) {
// before, prepend, append, after
let swap = el.getAttribute("hz-swap") ?? "replaceWith"
el.removeAttribute("hz-swap")
let targetQuery = el.getAttribute("hz-target") || el.id && `#${el.id}`
el.removeAttribute("hz-target")
let target = document.querySelector(targetQuery)
if (!target) continue
if (el.tagName === "TEMPLATE") el = el.content.cloneNode(true)
target[swap]?.(el)
}
frame.remove()
document.body.appendChild(frame)
location.replace("about:blank")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment