I have a title area on my webpage that has some background images that loop through it.
They are a bit high resolution and are above the fold so I don't want the browser to start loading any images other than the first one.
But I also want to randomize the order of the images.
The problem is that I am using a static web host (Netlify).
Some approaches I have considered:
What I want to do is run some JS code, run some short logic, and add some markup to the stream before the browser sees the entire HTML response. I can then provide a standard order in for people who have JS turned off and search engines that don't want to run JS.
I find that's exactly what document.write
does, isn't it?
All sources say to avoid document.write
like the plague. But I'm wondering 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 bad idea? Why? Is there a better way to achieve my wish?
Yes, this is not a good idea. This method is very old and has specific behavior that may vary from browser to browser. See https://developer.mozilla.org/en- US/docs/Web/API/Document/write for more information.
Just use modern methods like:
etc. Arrange elements randomly as these are renderer/browser safe.
However, a suggestion for your specific use case: the browser needs to load JavaScript first for it to work the way you want, but that may not happen. Images may still be loading in the order they originally appeared in the HTML source. I'd recommend moving this logic to the server if possible. Ultimately, any Javascript may not work for your use case. It might be possible to not include the images in the document itself and add them via JS (on random load), which would be my preferred approach.