If you find yourself needing to dynamically append a stylesheet to a page that you’re working on, here’s how:
Note that the most important thing to check for will be whether or not the stylesheet already exists in the DOM.
[cc lang=”javascript”]
$(function() {
// Setup a flag to toggle if we find the stylesheet
var bStylesheetExists = false;
$(‘link’).each(function() {
if($(this).attr(‘href’) === ‘plugin-style.css’)) {
bStylesheetExists = true;
}
});
// If we don’t find it, add it.
if(bStylesheetExists === false) {
$(‘head’).append(‘‘);
}
})
[/cc]
Note that this obviously assumes the plugin-styles.css is located in the same directory as your script. If not, you’ll need to adjust the href property and the comparison accordingly.
Diego says
In Less Lines…
$(function() {
var style = ‘plugin-style.css’;
if($(‘link[rel*=style][href=”‘+style+'”]’).length==0)
$(‘head’).append(”);
})