2

I've somewhat recently started building my own jQuery plugins to modularize some ideas I find myself using frequently. I've noticed many jQuery plugins have a separate js and css files to include, but I've begun to question that logic.

My question is, should I just be embedding the css in my JavaScript?

The Pros I can think of:

  • Reduced http requests
  • Plugin specific CSS isn't loaded if js is disabled
  • Ease of use - can be as easy as one copy-paste and the deed is done.

Cons?:

  • No seperation of concerns
  • More difficult to organize code how you want to
  • Confusing or difficult to edit core css for the uninitiated
  • can cause difficulty when releasing plugin updates
4

4 回答 4

1

I believe it is always better to separate the base plugin CSS file from your Javascript.

Mainly because if someone wants to make additions & changes to your CSS, they can do so in their own separate file, changing/replacing your css rulings easily. (That way if you made updates to the base CSS in a plugin update, it wouldn't conflict with theirs).

于 2012-08-14T14:08:53.417 回答
1

I'd definitely separate any non-trivial amount of CSS from your JS.

Let's go through the pros you have there:

Reduced http requests

If someone uses your plugin they will concat and minfiy all CSS files to one. If not, they're doing it wrong. So still one request for one main CSS file.

Plugin specific CSS isn't loaded if js is disabled

Really? They're already saving the requests for the JS files. I wouldn't care.

Ease of use - can be as easy as one copy-paste and the deed is done.

Well, I guess you can't, physically, disagree with that. But does it really matter? What if your plugin needs images? You can't include them as well.*

*yes, I know about data URI...

于 2012-08-14T15:34:39.017 回答
0

I myself have created few small plugins (just for fun) and i like the idea of embedding my CSS in the js file itself as its very much specify to what i am trying to do in the plugin. + the fear of plugin might now working properly if css is not loaded properly. Having said that, i guess we can really get good answers from this question which might make me change my coding styling.

于 2012-08-14T14:05:11.323 回答
0

If you want embedded CSS in JS, I found this lib helpful:

https://github.com/cssobj/cssobj

for use with jQuery:

https://github.com/cssobj/cssobj/wiki/Work-with-popular-JS-Lib

于 2016-08-03T14:58:03.210 回答