简体   繁体   中英

Is it bad practice to append style tag with multiple styles via javascript?

I have a question regarding style tags and Javascript. Many plugins or scripts come with a separate CSS file for styling. So, is it bad practice to avoid this, and use a style tag and append it to the head of the page, to then use those styles for your plugin?

For example, this code:

var style = document.createElement('style');

style.type = 'text/css';

style.innerHTML = '.hg-grid-item-4{ width: calc(24.25% - '+Options.padding * 2+'px); padding: '+Options.padding+'px; float: left; margin-bottom: 1%}';

document.getElementsByTagName('head')[0].appendChild(style);

would add some styling to the website without needing an external CSS stylesheet. Would this cause problems in older browsers?

Also, as you can see in my example, I used a variable for the padding and the width. Is there a way of doing this if you dedice to use an external CSS? Thanks in advance!

  • In most of the cases you do not need calc() in CSS - this will always slow things down a bit and in general is an over complication that can almost always be done in a more simple way
  • Doing things the way you did doesn't consider a non-js version. So not the best practice especially when you style something like .hg-grid-item-4 so I assume some some grid that you use. Will this not break badly with JS disabled ?
  • It makes the code less maintainable - not sure what would be the reason to mix logic with styling ? In general it is a better idea to use Sass for example and define your Options.padding there if this is not something that really really needs to be calculated with JS. Does it ?

Adding the style tag to the DOM with JavaScript is totally legal for JavaScript to do, however, this is not considered "best practice."

When writing code, it best to separate the view from your application logic. The easiest way to do this is to put all of your styles in a CSS file. Also, it has the added benefit of making your code easier for other developers to understand.

For more information:

In regards to your variable padding question, in vanilla CSS, this is not possible, in order to use variables in CSS, you would need to use a CSS Preprocessor, like SASS or LESS . However, I think this would be overkill for your problem, you can make flexible styles using Flexbox or using percents instead of fixed margins or padding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM