Skip to content

Instantly share code, notes, and snippets.

@dezren39
Forked from croxton/htmx-metadata.js
Created July 26, 2023 07:37
Show Gist options
  • Save dezren39/c580d47bf4663a4917cab2783b4f37f7 to your computer and use it in GitHub Desktop.
Save dezren39/c580d47bf4663a4917cab2783b4f37f7 to your computer and use it in GitHub Desktop.
Htmx swapping metadata
htmx.on('htmx:beforeSwap', (htmxEvent) => {
let incomingDOM = new DOMParser().parseFromString(htmxEvent.detail.xhr.response, "text/html");
// Transpose <meta> data, page-specific <link> tags and JSON-LD structured data
// Note that hx-boost automatically swaps the <title> tag
let selector = "head > meta:not([data-revision]), head *[rel=\"canonical\"], head *[rel=\"alternate\"], body script[type=\"application/ld+json\"]";
document.querySelectorAll(selector).forEach((e) => {
e.parentNode.removeChild(e);
});
incomingDOM.querySelectorAll(selector).forEach((e) => {
if (e.tagName === 'SCRIPT') {
document.body.appendChild(e);
} else {
document.head.appendChild(e);
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment