Kayote
Kayote

Reputation: 15617

Opinion on adding pre-styled class to a dynamically created element or adding stying there & then

In our web application, there are a lot of effects flying about. We are switching to creating as many elements dynamically, read: when needed, as possible.

Im curious about this technique I love using on elements, that is, creating a class with css styling in the style sheet, and then when the element is created with js, I merely add the class to the element to give it the styling I in the css file.

Is this really the best approach or would giving the styling in javascript (element.style = *) be better?

Note, memory is very important in our case so whichever uses less memory & rendering load would be better.

Upvotes: 0

Views: 61

Answers (2)

Trott
Trott

Reputation: 70065

Putting it in a separate stylesheet is usually considered best practice in terms of maintainability, separation of content from logic, all that good stuff.

But memory usage and render times, which you mention specifically as being very important to you, might be another matter.

You can use the web developer tools built into most modern browsers (e.g., Chrome Developer Tools) to try both approaches and profile for memory and render times. In Chrome Dev Tools, select Timeline, hit the record button at the bottom, load your page, do a few things on the page if that's relevant to you, stop the recording, and examine the memory usage and load time right there.

If your concern is animations, you may want to install Chrome Canary which has a third option (aside from Timelines and Memory) under Timelines that is something like Frames.

Upvotes: 1

Will
Will

Reputation: 20235

This depends on the case. If you have a set style for an element, which you just switch on and off, then adding/removing a class is the way to go. However, if you are consistently changing the style (i.e. in an animation) then modifying the style is better. In terms of memory, adding/removing classes would probably be more memory efficient.

Upvotes: 1

Related Questions