bigskysoftware / bigskysoftware/htmx
style-swap-to-head.js - Extension
- Dominant language
- JavaScript
- Stars
- 49.4k
- Forks
- 1.7k
- Avg merge
- 3d 22h
- Merged PRs (30d)
- 30
Description
This is an extension to transform responses with a -tag in the htmx response and put them in the head to make it WHATWG compatible, because validators do not like it. <style>-tags in body is a bad practise. You use this in [HTMX Animations](https://htmx.org/examples/animations/).
```
//==========================================================
// style-swap.js
//
// An extension to htmx 1.0 to put body styles in the head.
//==========================================================
(function () {
htmx.defineExtension("style-swap", {
transformResponse: function (text, _xhr, _elt) {
//has style tag
if (!text.match(/(<style(\s[^>]*>|>)([\s\S]*?)<\/style>)/im)) {
return text;
}
//find head
var head = document.getElementsByTagName("head")[0];
if (!head) {
return text;
}
//parse response
var dom = new DOMParser().parseFromString(text, "text/html");
var styles = dom.getElementsByTagName("style");
for (var i = 0; i < styles.length; i++) {
var styleInHead = null;
//check if style is already in head
if (styles[i].hasAttribute("id"))
styleInHead = document.getElementById(styles[i].id);
if (styleInHead) {
//replace with same id in head
head.replaceChild(styles[i].cloneNode(true), styleInHead);
} else {
//add to head
head.appendChild(styles[i].cloneNode(true));
}
//remove from response
styles[i].parentElement.removeChild(styles[i]);
}
return dom.documentElement.outerHTML;
},
});
})();
```
I would love to see it in the htmx lib. ❤️
Contributor guide
Research direction
Start by reviewing htmx's extension registration and transformResponse entry points, using the proposed style-swap extension as the behavioral reference. Confirm that style elements are moved into the document head, replaced by matching IDs, removed from the response, and left unchanged when no head exists; add it to the htmx library if the extension API supports that integration.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- frontend
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100