Shikha Gupta
Shikha Gupta

Reputation: 21

How to avoid unstyled flash of content when we dynamically change css files?

This is my jQuery function which replaces the CSS files

function BallyChangeTheme(theme) {
    var links = $("link");
    var _t = theme;
    $.each(links, function (i, link) {            
        var _h = $(link).attr('href');
        _h1 = _h.replace(/T.*e[0-9]/, _t);
        if (_h1 !== _h) {               
            $(link).attr('href', _h1);                
        }
    });
}

There are 15 link elements! The transition isnt smooth after the css files have been replaced. Any idea how to provide smooth user experience , when user opts to change theme ?

Upvotes: 2

Views: 335

Answers (1)

Danny Drinkwater
Danny Drinkwater

Reputation: 41

As @rory-mccrossan says, place all CSS in the same file but scoped under a different top-level class on the body, something like:

HTML

<body class="style-a">
    <a href="" class="btn" title="Toggle styles">Toggle styles</a>
</body>

CSS

.style-a {
    a {color: red;}
}
.style-b {
    a {color: blue;}
}

JS

$('.btn').on('click', function(e) {
    e.preventDefault();
    $('body').toggleClass('style-a').toggleClass('style-b');
});

Upvotes: 1

Related Questions