1

I have several CSS files generated in PHP.

I change the current CSS file with a click event.

But it make a nasty white flash effect between each change (only on the first load of them, the next times they are in cache and there is not bad effect).

How could I preload (but not display) this CSS file by the click event ?

$('.button').click(function(){
    // Here I would like to preload the file
    ...
    // Here I display it
    $("#css").attr("href","css.php?id="+$(this).attr('id'));
});

EDIT > Solution

/* HTML File */
<link type="text/css" rel="stylesheet" href="css.php?id=1" id="css"/>
<link type="text/css" href="css.php?id=2" id="nextcss"/>

/* JS file */
$('.button').click(function(){
    // Preload the file
    $("#nextcss").attr("href","css.php?id="+$(this).attr('id'));
    /* Here a lot of code with ajax...*/        
    // Here I display it
    $("#css").attr("href","css.php?id="+$(this).attr('id'));
});
2
  • can you make a demo at jsfiddle.net Commented Jan 22, 2012 at 4:26
  • I don't think that any demo is required for my question... This script works, but I just wanna add a preload Commented Jan 22, 2012 at 4:32

1 Answer 1

3

I'm assuming this "flash effect" means that, as the CSS is being loaded, the new rules are being applied incrementally, but you want all them to be applied at once. Is that right? Maybe you could append the newly created css element to the dom (ensuring it will start loading), but adjust its attributes so it won't be interpreted as a stylesheet (for instance, not using rel="stylesheet"). When it's done loading, you adjust it again with the right value, that should make the whole change appear instantly.

Another option (though that will require changing your css) would be creating a class, to be applied to the body, and making sure every rule references elements inside body.myclass. When the css is done loading, apply that class to the body.

Sign up to request clarification or add additional context in comments.

2 Comments

The white flash effect appear at the first load of each css, the second time they are in cache and there is no problem. Not using rel property doesn't use my css file... I don't understand your second solution (My english is not very good). I only want to preload the next css file in cache, how could I make it ?
Oh sorry !! I've just understood what you mean with the rel property ! Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.