21

I want to dynamically style all elements of a given selector in my DOM. I see more or less two ways about it. For the example below I'll use a p element and it's text-align attribute but I'm more interested in the pros and cons of the two possible ways of doing this than I am in specifically text-aligning paragraphs.

1. Inline (per element) Styles

var nodes = document.getElementsByTagName('p');
Array.prototype.forEach.call (nodes, function (node) {
     node.style.textAlign = "center";
});

2. Stylesheet

var sheet = (function() {
  // Create the <style> tag
  var style = document.createElement("style");

  // WebKit hack :(
  style.appendChild(document.createTextNode(""));

  // Add the <style> element to the page
  document.head.appendChild(style);

  return style.sheet;
})();

sheet.insertRule("p { text-align: center; }");

Typically I would go the route of inline styles, as it seems simpler and it ensures the style change would override the existing style sheets. But it occurs to me that for one: sometimes not overriding the style sheets might be preferable, and for two: it might be more performant to modify one style element than an unknown quantity of p elements. But that's just my assumption.

Performance wise, would there ever be a situation where applying inline styles to each individual element would be better than creating a style sheet? Assuming the answer might be dependent on how many elements I am styling, at one point does creating a style sheet become more efficient?

EDIT: To clarify why I'm asking the question, I'll explain a little about why I'm asking: I've recently turned a handful of JS hacks I've often copy-pasted and adapted between projects into a set of reusable CommonJS modules. They do things like setting all elements of a given selector the same height or width as the tallest or widest of the set in situations where the measure of the tallest or widest might be subject to change on a window resize or other triggers.

Here is a blog post about it: http://davejtoews.com/blog/post/javascript-layout-hacks

Here are the GitHub repos for the modules:

At this point, all these modules use inline styles, but I am thinking of switching them to stylesheets. I couldn't find a good answer about the pros and cons of either approach so I posted the question here.

8
  • 1
    Have you considered responsiveness? I believe that's where a cascading style sheet becomes a necessity. How are you going to add @media queries inline? Or are you going to do what CSS is doing out of the box via javaScript? Do you really think it's going to be faster?
    – tao
    Feb 24, 2017 at 0:12
  • Media queries are a good point. For the use case that drove me to ask this question, no media queries will be involved, but for the general question of inline vs stylesheet that's definitely a point for stylesheets.
    – dave
    Feb 24, 2017 at 0:24
  • There is a third way, that I personnaly prefer : CSS body.p_are_centered p { text-align: center } js : document.body.classList.add('p_are_centered'). Don't mess with the DOM when you don't need to. (Of course you can replace body with any parent node)
    – Kaiido
    Feb 24, 2017 at 4:48
  • why dynamic? our of interest and i guess helps understand the use case and therefore how performance may be important or affected.
    – Seabizkit
    Feb 24, 2017 at 13:18
  • @Kaiido: For the use case I have in mind css isn't an option, which is why I asked specifically about the difference between the two purely JavaScript solutions. I'll post another comment below, and edit the post to explain more about what I'm doing.
    – dave
    Feb 24, 2017 at 18:05

3 Answers 3

8

I don't have a good general answer to your question (and I'm not sure there is one), but I've run some experiments with the example you posted on Chrome 57.0.2987.98 beta, using the dev tools timeline.


Here is a breakdown of the work done in the single frame which updates 10,000 <p> elements with inline styles (left) and a dynamic stylesheet (right):

inline stylesheet


For comparison, here are the results for the same test with 100 <p> elements:

inline stylesheet


In summary, for a small number of elements, the difference is negligible. For a large number of elements, when using inline styles, the browser spends more time scripting (which is to be expected, since there is a heavy loop) and recalculating styles (I think this can be explained by the browser having to parse one style rule per-element rather than a single common style rule).

All other steps take approximately the same amount of time. In particular, the paint time does not increase when using inline styles.


For reference, I had used the following test page.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button id="add-stylesheet">Stylesheet</button>
    <button id="add-inline-styles">Inline</button>
    <script type="text/javascript">
        let stylesheet = document.getElementById('add-stylesheet');
        let inline = document.getElementById('add-inline-styles');

        stylesheet.addEventListener('click', addStylesheet);
        inline.addEventListener('click', addInlineStyles);

        function addStylesheet() {
            let style = document.createElement("style");
            style.appendChild(document.createTextNode(""));
            document.head.appendChild(style);
            style.sheet.insertRule('p { text-align: center }', 0);
        }

        function addInlineStyles() {
            let nodes = document.getElementsByTagName('p');
            for (let node of nodes) {
                node.style.textAlign = 'center';
            }
        }

        // initialize <p> elements
        init(10000);
        function init(numElements) {
            for (let i = 0; i < numElements; ++i) {
                let p = document.createElement('p');
                p.innerText = 'testing'
                document.body.appendChild(p);
            }
        }
    </script>
</html>
4
  • Thanks for this! I learned a little something about the Chrome dev tools in reproducing your tests. I notice that if I use 30 elements rather than 10,000, just about everything seems be faster with inline styles. As I suspected there appears to be a threshold at which stylesheets catch up to inline styles. Can you confirm this and add a note about it to your answer? I want to mark your answer as accepted since it got me 99% to what I needed, but I feel the information about the number of elements is important.
    – dave
    Mar 10, 2017 at 21:10
  • @dave thanks for pointing that out, I had wanted to note that the difference becomes insignificant for a small number of elements, but forgot to in my first draft. Please see the edit.
    – Igor Raush
    Mar 10, 2017 at 22:24
  • 1
    Thanks. Did you do any testing at even lower numbers? As I said above, on my machine I'm actually showing better performance with inline styles when the number of elements was 30. The difference is small enough that it probably is, as you say, insignificant on desktop. But it stands out more if I use the throttling feature of dev tools, which tells me that it could make a difference on a mobile device.
    – dave
    Mar 10, 2017 at 22:35
  • 2
    @dave I think at that point it becomes necessary to design a test which runs each update in a loop, ensuring a repaint on each iteration, and then averages the time. There is probably too much noise to get good results even from 100 elements. For example, the Hit Test slowdown doesn't really make sense to me. I will try to do something more robust when I get some free time and get back to you.
    – Igor Raush
    Mar 10, 2017 at 22:40
6

Pros and Cons of inline styles

There has been a lot of debate on this subject in the past couple years since React and JSX have gained enormous popularity.

I've tried a few solutions so I'll list them out here. First a general discussion..

CSS is basically the only language that advocates using a global namespace, and this is the number 1 reason people are moving away from straight CSS and heavy overarching frameworks. With flexbox, responsive layouts can be done in several lines of codes rather than an entire grid system such as you'd get with something like bootstrap.

CSS solved the issue of providing styles to documents in a reusable way, but as applications got more huge and more complex, and more 3rd party libraries with their own CSS was included, the chance for global namespace collisions became almost unavoidable. So much so that a few different patterns were authored and advocated for, such as BEM and SMACSS.

The react came along which made managing and creating reusable inline styles relatively straightforward. You could use all of javascript, which meant you could override styles using things like _.extend or Object.assign. This made for easy to share modules and packages which included components and their styles, and had the benefit of not requiring any sort of style loader, such as what is required when using webpack. It wasn't all roses, though. Things like :hover, other psuedo-selectors, and media queries are not supported in plain inline styles.

To get around these limitations, developers implemented events to trigger style changes, such as onmouseover for hover, and hooking into the window resize events for media queries. Soon thereafter, a library to standardize these js events, and define a CSS like API was created and gained popularity, called Radium. In the wild, Radium did not fair as well (believe me I tried). In large apps, none of the media queries could execute until all of the JS had been downloaded, which I don't recommend!

That led to the creation of a few new tools that take a different approach. These new generation of tools use styles defined in JS, but generate CSS. This gives you the full power of inline styles and the full power of CSS. Best of both worlds. Which library is the best probably depends on your use case, but those consist of Fela.js, Aphrodite, and JSS.

My favorite solution is Fela.js. Check it out at fela.js.org. Fela is probably the best performance you are going to get, and it is not specific to any particular framework. That being said it works well with React and React Native. It has a couple of neat features such as allowing you to access props from your styles. You set up a renderer in the head of the page. Fela works best with SSR, but also works purely client side depending on your needs. When using with SSR you can get blazing fast page loads because Fela optimizes the styles you've written into atomic css classes, and they are sent on back to the client on the initial request.

These tools are amazing if you are concerned about getting the fastest page possible. You can easily accomplish difficult patterns such as critical path css optimization, where the necessary styles are returned as part of the initial HTTP request, rather than a link to an external sheet that also has to be downloaded.

Lastly, I have to mention CSS modules. These do create an external stylesheet, but allow you to still have namespaced CSS per module. This allows you to write real CSS or SASS or etc, but comes with additional setup overhead. In webpack for example, you'd need to use a combination of fake style loaders and text extraction tools to create the .css file.

5
  • if you have more questions or this answer missed something, feel free to ask! Feb 28, 2017 at 23:54
  • Thanks for this. I don't think I want to include a library like Fela for the tools I'm building. I'm looking for strictly client side style changes, and rather simple changes at that. However, knowing that tools like this have chosen to go with stylesheets rather than inline styles is a possible sign that I should go that way as well.
    – dave
    Mar 1, 2017 at 19:06
  • 1
    well, they render CSS, not stylesheets per se. A stylesheet I would assume would be an external document. These just render CSS into the renderer which usually lives in the document head. (except css modules, that does render an external stylesheet) Mar 1, 2017 at 19:09
  • 1
    kind of a "virtual stylesheet" if you will. stylo seems similar to fela, as mentioned by @Hayko, but wouldn't hit the the caveat of having to re-render the page to update styles seems how the styles are converted to atomic css classes. Mar 1, 2017 at 19:12
  • I understand. I'm using the term "stylesheets" to refer to JS created CSS that gets appended to the document head, as opposed to inline styles. I'm not considering the use of external stylesheets, just weighing my options for javascript created styles.
    – dave
    Mar 1, 2017 at 19:12
2

It all depends on the context of what you are trying to accomplish. At my currently employer, I ended up creating a small library called stylo which is responsible for updating a dynamic stylesheet.

When the number of items you are trying to update is in the thousands, then updating via inline styles will be prohibitively expensive. The demo in the link above updates 6,400 items in a fraction of a second.

However if you are updating only a handful of items, updating the stylesheet might trigger a whole page re-render which wouldn't be the case if an inline style was updated.

5
  • Can you elaborate on why and when updating the stylesheet might cause a whole page re-render? For the use cases I have in mind I'm likely updating <50 items, however I'm trying to build a versatile tool. Thousands of items is going to be a performance drag in any case as the tools I'm building need to iterate over the items in order to detect their dimensions before applying style changes.
    – dave
    Mar 1, 2017 at 19:01
  • from what I gather, dynamically adding/removing/updating a stylesheet causes a whole page reflow which means that the layout of the page has to be recalculated, however changing an inline style only affects the layout of the element (although depending on what property was changed it might cause a page reflow anyway, e.g. changing the height of the root container of the page). Mar 2, 2017 at 9:31
  • @HaykoKoryun Is there are difference between adding/removing rules, and updating contents of existing rules?
    – Bergi
    Mar 2, 2017 at 19:25
  • @Bergi in general or when it comes to my library (there's a native way of updating the rules in a stylesheet, but it's more long-winded and harder to update I find)? Mar 2, 2017 at 21:15
  • In general, with the native way. I'd have guessed that when there's a change in the ruleset, it might rerender the whole thing, but when there's a change to the properties in a particular rule (that you of course would need to have reference to, therefore I assumed the native CSSOM) it might only apply those. How did you gather your findings, have you benchmarked your library?
    – Bergi
    Mar 2, 2017 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.