简体   繁体   中英

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?

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'
    })
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM