开发者

CSS for cross-site widget, best practice?

So I've got code that people can cut+paste a widget into their site with (similar to google analytics or the Google maps plugin, if you've seen those).

I've got a whole area that needs to be styled somehow. Now, I can either do this by manually reading config data from an object like

var x = {idWhatever: {bg-color: red, etc....}}

Or I 开发者_Python百科could document.appendChild("style")

Or I could inline all the css (I'd rather not).

Whatever happens, I can't be messing up other people's pages when this gets dropped in.

Any thoughts on the best way to deal with this?

edit: in theory, I may be able to use the data-uri to send the CSS in the same request.


I would recommend that you carefully choose element classnames and ids such that they are all prefixed with the name of your widget (like <myWidget>_mainDiv and .<myWidget>_headerText). Then make sure your styles are only targeting elements with (or at least, elements within elements with) these ids/classnames.

Then include your stylesheet either using the approach described here or with the document.appendChild("style") method. Ideally you want to keep your CSS in its own file, or at least somewhere where you can still write and maintain it like CSS. Which you can't really do if you stuff it inside of some object or if you inline it.


Give people two options:

  1. Styles passed as a parameter (object).
  2. Styles applied using your classnames.

In the first case you probably know what to do.

In the second case, add meaningful class names, as @aroth suggests in the answer (so you minimize risk of interfering with classes applied on the page that implements your widget).

It could look like this:

  1. If someone does not give style parameter, then default styles are used. If not, then
  2. If he gives any styles, these styles overwrite appropriate styles. If not, then
  3. If he passes eg. false instead of styles parameter, then do not apply any styles and rely on CSS classes and trust that user will apply styles by himself.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜