Practices for keeping JavaScript and CSS in sync?

Posted by Rene Saarsoo on Stack Overflow See other posts from Stack Overflow or by Rene Saarsoo
Published on 2011-01-08T21:45:19Z Indexed on 2011/01/08 21:53 UTC
Read the original article Hit count: 349

I'm working on a large JavaScript-heavy app. Several pieces of JavaScript have some related CSS rules. Our current practice is for each JavaScript file to have an optional related CSS file, like so:

MyComponent.js  // Adds CSS class "my-comp" to div
MyComponent.css // Defines .my-comp { color: green }

This way I know that all CSS related to MyComponent.js will be in MyComponent.css.

But the thing is, I all too often have very little CSS in those files. And all too often I feel that it's too much effort to create a whole file to just contain few lines of CSS - it would be easier to just hardcode the styles inside JavaScript. But this would be the path to the dark side...

Lately I've been thinking of embedding the CSS directly inside JavaScript - so it could still be extracted in the build process and merged into one large CSS file. This way I wouldn't have to create a new file for every little CSS-piece. Additionally when I move/rename/delete the JavaScript file I don't have to additionally move/rename/delete the CSS file.

But how to embed CSS inside JavaScript? In most other languages I would just use string, but JavaScript has some issues with multiline strings. The following looks IMHO quite ugly:

Page.addCSS("\
  .my-comp > p {\
    font-weight: bold;\
    color: green;\
  }\
");

What other practices have you for keeping your JavaScript and CSS in sync?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about css