jQuery plugin for switching stylesheets

It has been almost three years since I wrote my top ranking post on this blog: Applying stylesheets dynamically with jQuery. It was a quick and dirty example of a testing scenario pulled together for a colleague but it has become my number one linked post. It is still the post that gets the most hits every month because it is the first hit on Google for jquery add stylesheet which seems to be a lot of people has trouble with.

So, I felt it was time to do another post on the subject considering I’ve been using jQuery more or less every day these last three years.

jQuery Plugin

I’ve created a simple jQuery plugin for adding or switching out stylesheets dynamically and interactively and it can be used like this:


    <li><a href="#" rel="1.css">Apply Stylesheet 1</a></li>
    <li><a href="#" rel="2.css">Apply Stylesheet 2</a></li>
    <li><a href="#" rel="3.css">Apply Stylesheet 3</a></li>

jQuery hookup

$('a').click(function () {
    return false;

jQuery Plugin

$.stylesheets = (function () {
    var stylesheets,
    add = function (cssfile) {
        $('head').append('<link href="' + cssfile + '" rel="stylesheet" />');
        return stylesheets;
    clear = function () {
        $('head link[rel=stylesheet]').remove();
        return stylesheets;
    return stylesheets = {
        add: add,
        clear: clear
} ());

Download source / demo

Comments (2) -

  • Cazare Sovata

    2/8/2014 7:20:59 PM | Reply

    The plugin is very simple, but I am sure that it works really nice and you certainly not have to worry because of this.

  • Stan

    2/8/2014 7:21:55 PM | Reply

    I get an error in IE 8 (IE9, but browser mode:IE8 and document mode:IE8)..could also be in 9 but haven't checked "SEC7113: CSS was ignored due to mime type mismatch". As far as I can tell the css is still being applied....this is inside a facebook app, so there could be some cross-domain issues. It's easy enough to set the header on the server side, but haven't had any luck setting it with javascript, or even know if it's possible.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.