Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS to my JQuery Plugin

I'm writing a JQuery component plugin that requires some minimal default css. (The css is required for the component's functional layout- not just style dressing) Should I:

  • Write a separate .css file and dynamically load it in my plugin code (How would I do this?)
  • Apply the css attributes directly in my plugin code using JQuery's .css(...)

It seems the second option would be a more secure way of ensuring my component gets the css it needs. Thoughts?

like image 917
Yarin Avatar asked Mar 10 '11 14:03

Yarin


1 Answers

I'm a fan of keeping CSS in a separate file and then importing it using the plugin.

Overtime, this makes it easier to maintain and it makes it easier for users or future developers to work with your plugin rather than digging through JavaScript source (which will likely grow overtime).

To apply a stylesheet with jQuery, you can do this:

$(function() {
  $('head').append('<link rel="stylesheet" href="plugin-styles.css" type="text/css" />');
});

Obviously, you'll need to know the path to the CSS file but If you ship a css directory with your plugin, this shouldn't be problem.

As far as "ensuring [your] component gets the css it needs," the first option will work file as long as you make sure your elements have a unique identifier (classname or ID) that the JavaScript source can access.

If you want to make sure that you're not loading the stylesheet multiple times, you can do something like this:

$(function() {

  var bStylesheetExists = false;
  $('link').each(function() { 
    if($(this).attr('href') === 'plugin-style.css')) {
       bStylesheetExists = true;
    }
  });

  if(bStylesheetExists === false) {
    $('head').append('<link rel="stylesheet" href="plugin-styles.css" type="text/css" />');
  }

});
like image 178
Tom Avatar answered Oct 06 '22 01:10

Tom