In-lining Styles Client Side
Tags: javascript, style, inline
Published: 2021-11-12 07:05:29

Wanting to [in-line styles](https://dev.to/thumbone/html-on-the-clipboard-oh-what-shall-we-copy-21g9#-raw-style-endraw-attributes-aka-inlining-style-the-hard-way-sweatdrops), the first port of call, not least given Chrome-based browsers seem to in-line styles when using [Select and Copy](https://dev.to/thumbone/copy-to-clipboard-the-options-1a07#select-and-copy-thumbsdown), is to find an existing solution. Alas that search yielded no fruit. 

Here are some options that a search on the web uncovers.

- [Juice](https://github.com/Automattic/juice), 
- [inline-css](https://www.npmjs.com/package/inline-css), 
- [css-inliner](https://www.npmjs.com/package/css-inliner)

But none of them work well here. Let's look at why ... (or if you don't care why not, just jump straight to the [Native Javascript](#native-javascript-thumbsup) solution at the end).

## Juice :thumbsdown:

Looks sort of nice but oh so complicated. So many options. On the up side they do clarify that it can and does run client-side, and provide a test site:

https://automattic.github.io/juice/

And it in-lines `<style>` tagged HTML wonderfully. Works well.

Still, it's overkill, brings with it dependencies [cheerio](https://github.com/cheeriojs/cheerio), [mensch](https://github.com/brettstimmerman/mensch) and [slick](https://github.com/subtleGradient/slick) and a look into the code behind the on-line demo makes rapidly clear that Juice is parsing the style sheets and applying them in what looks to be, must be, a product of its age. It has over 1500 lines of Javascript and the [repo](https://github.com/Automattic/juice) was created in 2011 - the state of Javascript was woeful then compared with today (though not as woeful as in [2001](http://www.jiehuang.net/wordPress/uncategorized/ecmascript/) :smirk:).

So we have to give Juice full credit and admiration for its age and endurance, and that it's still being maintained and is useful. But I'll respectfully pass it by as I'm looking for a minimalist, native Javascript solution as far as possible, using the state of Javascript in 2021 a whole decade later (which in IT terms is an eon).

## inline-css :thumbsdown:

Immediately disconcerting is the [npm](https://www.npmjs.com/) documentation for this package. It says simply "Inspired by juice" and fails to tell us why the authors felt that embarking on a new project was worth their while. It hints at the fact that it's better than [Juice](#juice-thumbsdown) in some way or other (why else start a new project inspired by it?), but lays no claim as to if or how that might be the case. A dark horse.

The github repo dates to 2015 and so, it's not as long-in-the-tooth as Juice, but still, it likely leans on a more meager JavaScript standard than we have available today and quite possibly, like Juice resorts to parsing CSS code and interpreting it. It has about 1700 lines of Javascript and so is even larger than Juice! The last code contributions on [github](https://github.com/jonkemp/inline-css) are early 2020 so at least it's being maintained which is good.

Still, it also depends on [cheerio](https://github.com/cheeriojs/cheerio), and so falls a little short of a native solution but worse, it does not provide us with any suggestion as to run-context (server side or client side). 

It's on npm, which is [Node.js](https://nodejs.org/) which suggests server-side JavaScript. It doesn't rule out that it  works client-side, but there is zero indication provided that it does nor a test site, the way Juice provided. And like it or not, I associate npm primarily with Node.js and server side applications (rightly or wrongly).

So for my needs, it goes respectfully into the too-hard basket. Failed, in a sense, by the poor quality of its own introductory presentation. An irony, because there is some nice documentation there, just not a nice introduction that spells out whether it runs client-side or not, how to if so, and how it's different from Juice and why we'd use it. All the obvious questions I have surfing in on it.

## css-inliner :thumbsdown:

Long story short, the introductory documentation fails this package even more than that for [inline-css](#inlinecss-thumbsdown) did. Again, it's on npm, and so looks targeted at server-side use and makes no effort to mention the other two (Juice or inline-css), or differentiate itself from them. The [github repo](https://github.com/broadly/css-inliner) dates back to 2015 as well and so it looks at some level to be an example of modern parallel development, this and inline-css emerging at the same time. And unsurprisingly, it again has around 1600 lines of JavaScript. The last code contribution was 2020 so again, at least  it's being maintained which is good I guess.

Still, no hint as to the run-context it supports (server-side and/or client-side) but hints, via its npm references and templating languages that it's a server-side tool not a client-side tool. Which doesn't rule out client-side application but again no claim that it works in that context, and no tips on how (if it does) and no demo site, so it's a respectful pass. Still seeking a lean native Javascript solution in preference to some pet project lacking clarity and exhibiting bloat. 

### Native Javascript :thumbsup:

The failure to find an existing solution, leads me to (seeking) a native JavaScript implementation and the journey of discovery that lies behind that.

[`document.styleSheets`](https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets) provides us with a collection of [`CSSStyleSheets`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet) and [`CSSStyleSheet.rules`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/rules) in turn provides all of the [`CSSStyleRules`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule) in use and [`Element.matches()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/matches) tells us if [`CSSStyleRule.selectorText`](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule/selectorText) applies to a given element. 

[`window.getComputedStyle()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle) provides rapid access to the complete set of [computed styles](http://xahlee.info/js/css_whats_computed_style.html). That is, crucially it has taken all those styles that position things relative to the browser window and calculated where, in real coordinates it landed. Among other things. Crucially, it also has resolved all of CSS variables. It describes what an element actually looks like on the screen, rather than in the abstract CSS.

We can use the style sheets and the computed styles to update the [style](https://www.w3schools.com/jsref/prop_html_style.asp) attribute of each element and then, when all is done the [`innerText`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText) and the [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) or [`outerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML) are available for the the `text/plain` and `text/html` MIME parts respectively.

Given we're in-lining styles, and we don't want to actually change the element in the DOM (we're just aiming to copy it to the clipboard in one form or another), we have to take a copy of the DOM element and in-line the styles on that. We have to use the computed style from the source element however as it is rendered on screen and the copy is not (hence has not got computed styles). To wit, we will have a source and target element one that is in the DOM and provides computed styles, and one that is not in the DOM and receives in-lined style attributes.

Importantly an implementation like this is maybe 200, or 300 lines of JavaScript and not 1500.

That more or less covers us and we have a terse native JavaScript in-lining solution! 

But ... performance, performance ... turns out that it's not slow, but it's not fast either, let's take a look at performance next, before we dive into an actual code implementation of the above schema - next week's article.