Demo: https://tuanphan.squarespace.com/random-bg-image?noredirect
Password: abc
#1. First, you add a section with a random image (You can use a colored image, with a color the same as the site color).
Because every time the page refreshes, this image will display for about 1 second before a new image appears.
#2. Use Squarespace ID Finder to find Section ID
Something like this:
#3. Use this code to Page Header Code Injection
<script> document.addEventListener('DOMContentLoaded', function() { var images = [ 'https://cdn.pixabay.com/photo/2023/05/05/06/19/street-7971714_1280.jpg', 'https://cdn.pixabay.com/photo/2024/02/17/15/02/bird-8579496_1280.jpg', 'https://cdn.pixabay.com/photo/2023/09/20/17/23/frog-8265261_1280.jpg', 'https://cdn.pixabay.com/photo/2023/05/25/18/10/flowers-8017976_1280.jpg', 'https://cdn.pixabay.com/photo/2024/01/31/15/55/chicken-8544360_1280.jpg', 'https://cdn.pixabay.com/photo/2023/09/21/17/57/sunset-8267343_1280.jpg' ].sort(() => .5 - Math.random()); var randImage = images[0]; var imgEl = document.querySelector('section[data-section-id="64d348c1cc56d277853b026d"] .section-background img'); imgEl.src = randImage + '?v=' + Math.random(); // add a query parameter to prevent caching imgEl.setAttribute("srcset", ""); }); </script>
#4. Explain
#5. In case you want the images to appear in the correct order of the image url you entered in the code, remove #3 code and use this new code.
<script> document.addEventListener('DOMContentLoaded', function() { var images = [ 'https://cdn.pixabay.com/photo/2023/05/05/06/19/street-7971714_1280.jpg', 'https://cdn.pixabay.com/photo/2024/02/17/15/02/bird-8579496_1280.jpg', 'https://cdn.pixabay.com/photo/2023/09/20/17/23/frog-8265261_1280.jpg', 'https://cdn.pixabay.com/photo/2023/05/25/18/10/flowers-8017976_1280.jpg', 'https://cdn.pixabay.com/photo/2024/01/31/15/55/chicken-8544360_1280.jpg', 'https://cdn.pixabay.com/photo/2023/09/21/17/57/sunset-8267343_1280.jpg' ]; const oldImg = localStorage.getItem('bgimg'); const oldIdx = images.findIndex(img => img === oldImg); const newIdx = oldIdx < images.length - 1 ? oldIdx + 1 : 0; var randImage = images[newIdx]; localStorage.setItem('bgimg', randImage); var imgEl = document.querySelector('section[data-section-id="64d348c1cc56d277853b026d"] .section-background img'); imgEl.src = randImage + '?v=' + Math.random(); // add a query parameter to prevent caching imgEl.setAttribute("srcset", ""); }); </script>