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:
It seems the second option would be a more secure way of ensuring my component gets the css it needs. Thoughts?
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" />');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With