'Re-order divs randomly before page load?

I've been working on improving the Google Page Speed of my site.

It's nearly a perfect score except for Largest Contentful Paint.

I've worked out this is because my Carousel at the top of my page is hidden on page load, then I'm using javascript to shuffle the slides randomly before showing it:

shuffle(selector) {
    let $elements = document.querySelectorAll(selector)
    let array = []
    $elements.forEach(($el) => {
        array.push($el.cloneNode(true))
    })
    $elements.forEach(($el, i) => {
        $el.replaceWith(array[i=Math.floor(Math.random()*array.length)])
        array.splice(i,1)
    })
},

init() {
    const $carousel = document.querySelector('.carousel.shuffle'),
        
    if ($carousel) {
       this.shuffle('.carousel-card')
       $carousel.style.opacity = 1
    }
},

This causes a delay because it has to wait until the DOM is fully loaded then run my script and therefore shows the LCP (the first slide image) later than it would otherwise.

Is there any way to shuffle the div's before the page loads?

I'm using Vite and Alpine.js.

My page is cached so I don't think it can be done server-side.

I was thinking I could maybe use CSS like this answer but I'm not sure random is possible in CSS?



Solution 1:[1]

you could try to speed up the dom update by using createDocumentFragment api (instead of having an update for each element move)

something like:

let elements = document.querySelectorAll(selector)
const frag = document.createDocumentFragment();
const shuffledList = Array.from(elements).sort(() => (Math.random() > .5) ? 1 : -1);
for (let item of shuffledList) {
  frag.appendChild(item);
}
document.querySelector('.carousel.shuffle').appendChild(frag);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 basdanny