简体   繁体   中英

Random CSS file loading - not working in IE8 (7?)

I'm loading a CSS file dynamically using a little bit of randomization:

 var cookie = $.cookie('necgroupcolour', { path: '/' });

    if (cookie == null) {
        var rnd = Math.floor(Math.random() * 3);

        $.cookie('necgroupcolour', rnd, { path: '/' });
    }

    switch ($.cookie('necgroupcolour', { path: '/' })) {
        case "0":
            $('head').append('<link rel="stylesheet" type="text/css" href="/css/purple/HomeMaster.css" />');
            break;

        case "1":
            $('head').append('<link rel="stylesheet" type="text/css" href="/css/blue/HomeMaster.css" />');
            break;

        case "2":
            $('head').append('<link rel="stylesheet" type="text/css" href="/css/green/HomeMaster.css" />');
            break;

        default:
            $('head').append('<link rel="stylesheet" type="text/css" href="/css/purple/HomeMaster.css" />');
    }

This works fine in Firefox, Safari, Chrome, but not in IE8 or lower.

When running this through Fiddler and checking the source you can see that no CSS file is getting loaded.

Any ideas how I could solve this?

Maybe try put this code in head and use document.write. ugly, but will work....

I know this may be too late, but it may help someone else.

Instead of using

$('head').append('<link rel="stylesheet" type="text/css" href="PATH_TO_CSS_FILE>');

use the following code:

var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", PATH_TO_CSS_FILE);
document.getElementsByTagName("head")[0].appendChild(fileref);

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