Search code examples
javascripthtmlcssweb-componentcustom-element

Multiple pre-defined styles or dynamically change inline style?


I am working on a custom element for playing cards. I use SVG images as the background and I'd like them to change the background image whenever the suit or rank attributes are changed.

As far as I know there are two ways to do so - one is to use the "attributeChangedCallback" method:

static get observedAttributes() {return ["suit", "rank"];}
attributeChangedCallback(name, oldValue, newValue) {
  this.style.backgroundImage = `url(...)`;
}

and the other is to have a lot of CSS attribute selectors:

:host([suit="clubs"][rank="4"]) {
  background-image: url(...);
}
:host([suit="clubs"][rank="5"]) {
  background-image: url(...);
}
...

They both work but the JS way adds inline styling which I'd like to prevent and the CSS way is very big. Are there any huge performance differences I need to consider?


Solution

  • There should not be huge performance differences, or only if you have hundreds or thousands of custom elements in the same page.

    In the latter case you should test both solutions in operational conditions, then choose the better.

    If it's not the case, it will depends on how your project is managed: is it the same team the maintains the CSS and the JS files or not.