Flickering Style Styles

I have a website with 2 styles, one for day and one for night reading. I have an image with an event onclickto call a function to change a stylesheet. The problem is that for new visitors, when they first click the button, the page goes into a completely uninstalled (that is, without a style sheet) only for half a second, then a new one arrives. I know the reason for this is because I delete the rel="stylesheet"current sheet before adding it to a new one. Is there a way to improve the function so that there is no short delay, even for new visitors? Thank.

function changeStyleSheet() {
    var a = document.getElementById('stylesheet1');
    var b = document.getElementById('stylesheet2');
    var now1 = $(a).attr('rel');
    var now2 = $(b).attr('rel');
    if (now1 == 'stylesheet') {
        a.setAttribute('rel', 'alt-stylesheet');
        b.setAttribute('rel', 'stylesheet');
    } else {
        b.setAttribute('rel', 'alt-stylesheet');
        a.setAttribute('rel', 'stylesheet');
    }
};
+3
source share
4 answers

? rel , , rel , ?

rel HTML, javascript .

+3

- :

JavaScript

function changeStyle() {
    document.getElementById('stylesheet').href = 'style2.css';
}

HTML

<input type="button" onclick="changeStyle();"/>
<link rel="stylesheet" href="style1.css" id="stylesheet">

this

:

function changeStyle() {
    var a = document.getElementById('stylesheet').href;
    if (a === 'style1.css') {
        document.getElementById('stylesheet').href = 'style2.css';
    } else {
        document.getElementById('stylesheet').href = 'style1.css';        
    }
}​
+1

, , id body. body , , div id. CSS id .

JavaScript:

var sel = document.getElementById('styles'),
    b = document.getElementsByTagName('body')[0];
sel.onchange = function() {
    b.id = this.value;
};​

CSS:

#styles1 h1 {
    margin-top: 1em;
    color: #f00;
    background-color: #000;
    text-align: center;
    font-size: 2em;
}

#styles1 div {
    width: 80%;
}

#styles2 h1 {
    margin-top: 1em;
    color: #000;
    background-color: #fff;
    text-align: right;
    font-size: 1.5em;
    font-style: italic;
}

#styles2 div {
    width: 50%;
    margin: 0 auto 1em auto;
}

/* the following is for the element holding the style-switcher select */
#styles1 #themes,
#styles2 #themes {
    width: auto;
    position: absolute;
    top: 0;
    left: 0;
    background-color: #fff;
}​

JS Fiddle demo.

, , . , , , .

+1

, /:

( ):

  • 1 -
  • 2 -
  • 1 -

, ( , , , /).

If this is a problem, you might consider doing something to make the style sheet look awesome - for example, fading the page / elements before changing the style, changing the style, and then fading.

If this is not a problem, you should be able to use the approach provided by jacktheripper

0
source

All Articles