Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style-swap-to-head.js - Extension #2503

Open
ditzel opened this issue Apr 24, 2024 · 0 comments
Open

style-swap-to-head.js - Extension #2503

ditzel opened this issue Apr 24, 2024 · 0 comments

Comments

@ditzel
Copy link

ditzel commented Apr 24, 2024

This is an extension to transform responses with a <style>-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.

//==========================================================
// 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. ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant