Search code examples
javascriptjqueryinternet-explorerinternet-explorer-9conditional-comments

How can I use JavaScript/jQuery to conditionally add a stylesheet?


I've looked online for a suitable solution to the following issue and I can't seem to find a useful workaround;

We're using Umbraco CMS to display a client's website, this isn't allowing us to add in the usual conditional comments that one would do in the < head > of the HTML. Therefore I've been trying to find a way to get JavaScript or jQuery to conditionally display an IE9 specific stylesheet.

The options I've seen so far are as follows:

if ($.browser.msie && parseInt($.browser.version, 10) === 7) {
    $('head').append('<link>', {
        rel:  'stylesheet',
        type: 'text/css',
        href: 'css/ie9.css'
    });
}

And using conditionizr (which hasn't worked due to a console error on the ".add" function).

Any ideas on this?


Solution

  • Instead of passing the tag name and its properties as two separate arguments to append(), you need to pass one fully constructed jQuery object (or HTML string).

    $('head').append(
        $('<link>', {
            rel:  'stylesheet',
            type: 'text/css',
            href: 'css/ie9.css'
        })
    );