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'));
});
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 insidebody.myclass. When the css is done loading, apply that class to the body.