Created
October 13, 2022 13:46
-
-
Save croxton/8a12a19e10f3b8a395d5546ff070aa93 to your computer and use it in GitHub Desktop.
Htmx swapping metadata
This file contains 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
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