ukijake
ukijake

Reputation: 41

Change entire CSS file on refresh

All other questions I've found relating to this are about changing specific elements, or changing the CSS file with a button, but what I'm looking to find out is:

Is there a script that will swap an entire CSS file whenever the page is refreshed?

I.e. I've got my core style.css and supplementary {color}.css files which replace certain elements in style.css, and I'd like those supplementary CSS files to be loaded randomly on refresh.

Sorry, I don't even know where, to begin with this. Hopefully, someone can offer some pointers?

Thank you.

Upvotes: 3

Views: 69

Answers (2)

kb.
kb.

Reputation: 2005

All you need to do to load a CSS-file with Javascript is to add a <link> element to the DOM/body and it will be loaded automatically.

So in your <head> section you could include a <script> tag that just randomly selects a color.css from an array and generate the link tag, preferably as early as possible in the file to prevent flickering.

<script>
  var colors = ['red.css', 'blue.css', 'green.css'];
  var colors_idx = Math.floor(Math.random()*colors.length);

  document.write('<link href="'+colors[ colors_idx ]+'" rel="stylesheet" type="text/css" />');
</script>

(PS. There are cleaner ways to inject HTML, keeping it concise to focus on the solution. Use your favorite approach, document.write can be a bit fickle.)

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074138

Fundamentally this is just a matter of picking something at random, e.g.:

<head>
<!-- ... -->
<script>
var sheets = ["sheet1.css", "sheet2.css", "sheet3.css"];
var sheet = sheets[Math.floor(Math.random() * sheets.length)];
document.write('<link rel="stylesheet" href="' + sheet + '">');
</script>
<noscript>
<link rel="stylesheet" href="sheet1.css">
</noscript>
<!-- ... -->

(One of the rare cases where document.write isn't actually a bad solution.) Note the noscript fallback will always use the same stylesheet on browsers with JavaScript disabled.

Upvotes: 3

Related Questions