ackh
ackh

Reputation: 2052

How to update multiple CSS properties using JavaScript in one operation

Let's say I have the following CSS rule in a stylesheet:

.demo-rule {
  --custom-prop-1: 12px;
  --custom-prop-2: 54px;
  width: 100%;
  height: 100%;
  /* several more properties are set here */
}

Now, that rule is applied to multiple HTML elements and I want to recalculate and reassign the values of the two custom CSS properties --custom-prop-1 and --custom-prop-2 using JavaScript. Currently, I'm first obtaining the style of the corresponding rule in the stylesheet as follows:

const style = this.shadowRoot.styleSheets[0].rules[0].style;

Once I got that I calculate and set the values of those properties:

const valueProp1 = /* calculation */;
const valueProp2 = /* calculation */;
style.setProperty("--custom-prop-1", valueProp1);
style.setProperty("--custom-prop-2", valueProp2);

The problem I see is that I edit the style twice. This might force the web browser's rendering engine to recalculcate the layout twice. I would like to change both properties in one atomic operation to prevent that. Is that possible somehow?

Upvotes: 0

Views: 1082

Answers (2)

dave
dave

Reputation: 64657

This might force the web browser's rendering engine to recalculcate the layout twice.

It won't. The browser will wait for the JS to finish, it can't rerender until the JS reaches a "stopping point", for example below, we wait half a second to do anything (just to let the initial div render), then change it to a blue background, then have a busy loop that should take a while, then make it green. You will never see the blue div.

setTimeout(() => {
  const test = document.getElementById('test');
  test.style.background='blue';
  for (let i = 0; i < 10000000; i++) {
    test.style.background='green';
  }
}, 500);
#test {
width: 10px;
height: 10px;
background: red;
}
<div id="test"></div>

Upvotes: 1

Pytth
Pytth

Reputation: 4176

Since both those props have their own individual values, you would need to update them separately. The only way I could think for you to NOT have to do that, is for them to be declared in a style tag on the page that you edit at the same time via javascript before placing them back on the page. That all said, I think you might be worrying a bit too much about optimizing this. I would be highly surprised if you ran into performance issues by changing those values as you did above.

Upvotes: 1

Related Questions