1

Is it better from performance standpoint / a more efficient use of memory to have the CSS be created with the dynamically generated HTML elements, or to have the classes predefined in a CSS file waiting to be used?

I could imagine that having CSS sitting waiting to be used could make the CSS file unnecessarily big, whereas using JS to create the CSS could be a less efficient use of memory and processing power.

Would love to hear others' thoughts on it.

4
  • Even large CSS file have the advantage of being cached in the browser. CSS in the page has to be loaded again and again. There is usually no need for megabytes of CSS - can you share code how much that would be? Commented Mar 4, 2022 at 9:00
  • I havent yet written the code :D but it wouldnt be too much, like pretty much just display:flex; and justify-content:space-around; type of css. Im just thinking would it be better to have it wait in the css file to be used, or dynamically generated along with the html Commented Mar 4, 2022 at 9:06
  • 1
    You will not have a completely new style for every div. Your examples were static styles - using a class for that style is certainly a better use of ressources. Commented Mar 4, 2022 at 9:11
  • 1
    yeah thats true all these elements will have the same styling, Commented Mar 4, 2022 at 9:12

3 Answers 3

2

I vote for using css classes in separate file :

  1. To separate the display from the processing or the traitement
  2. To be able to manage any changes in the future
  3. Having the possibility to make your CSS dynamic with CSS Custom Properties
  4. Possibility to use css Modules
  5. Take all css advantage
Sign up to request clarification or add additional context in comments.

Comments

1

Personally, I prefer having things separate, since it's easier to find/read/update later one. Having a bunch of CSS styles mixed in with JS could make it hard to read and maintain in the long run.

I also wouldn't worry about optimization until you feel that your code is taking a while to load.

2 Comments

Ok yeah that makes sense, keep the the best practices
I agree with you, I would add that you can also let multiple sites of your website be using the same CSS (e. g. for styling the navbar) and later, you just have to update the one CSS file and not every site if you want to edit the CSS.
0

Defined in a css file, is a good practice. If you need to update the css after generating html, Then it will be a good to define in css classes.

1 Comment

Ok, fair enough, keep it standard

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.