I have a header area on a web page with some background images which get cycled through.
They're somewhat high-res, and it's above the fold, so I don't want the browser to start loading any image except the first one.
But I'd also like to randomize the order of the images.
The complication is that I'm using a static web host (Netlify).
Some approaches I've considered:
- Put the elements in the document as usual, then have Javascript query for them and randomize their order. I'm reluctant, because I think the browser will already be off to the races loading the first image which arrives in the HTML, before it gets randomized to some other position. I want to avoid that.
- Randomize with some server code. But I don't want to; I'm not going to run a server just for this feature.
- Write every possible combination, or at least a handful of combinations, as separate HTML files, and randomize via URL rewriting in an edge function. Seems sort of messy. I don't want to use an edge function if I don't have to, since it's just one more quota to worry about.
- Write some logic in an edge function which intercepts the page response and mutates it. Less messy in terms of files being served, though the code itself will be a lot more messy. Plus the same aversion to running an edge function.
What I want to be able to do is have some JS code run before the browser has even seen the whole HTML response, run some brief logic, and add some markup to the stream. And then I can have the standard order in a <noscript>
for people with JS turned off and for search engines which don't want to run JS.
It occurs to me that this is exactly what document.write
does, is it not?
All resources say to avoid document.write
like the plague. But I wonder if this is a rare valid use case?
<html>
<body>
<p>This seems to work, and I kind of think it's not a terrible idea.</p>
<script type="application/javascript">
// Standard Fisher-Yates shuffle; not relevant
function shuffle(array) { let i = array.length, j; while (i != 0) { j = Math.floor(Math.random() * i); i--; [array[i], array[j]] = [array[j], array[i]]; } return array; }
const paras = [
"<p>para 1</p>",
"<p>para 2</p>",
"<p>para 3</p>",
"<p>para 4</p>",
];
shuffle(paras);
document.write(paras.join(""));
</script>
<noscript>
<p>para 1</p>
<p>para 2</p>
<p>para 3</p>
<p>para 4</p>
</noscript>
<p>Change my mind.</p>
</body>
</html>
Is this a terrible idea? Why? Is there a better way to do it, meeting my wishlist?