DEV Community

Discussion on: I made my website 28ms faster with content-visibility 🤓

 
marcellothearcane profile image
marcellothearcane • Edited

The problem is each div can have a wildly different height based on content and the browser width (because of responsive image layouts).

I've done it on the divs because a) they are 'slices' from my CMS so it was easy, and b) because if the top of the div is visible on page load, there's no benefit.

I'm messing around with ResizeObserver and can remove the content-visibility once the element is rendered which fixes the issue after the initial scroll-down:

// Vue
mounted () {
  const observer = new ResizeObserver(entries => {
    for (const entry of entries) {
      if (entry.target.getBoundingClientRect().height > 0) {
        observer.unobserve(entry.target)
        entry.target.classList.remove('content-visibility-auto')
      }
    }
  })

  for (const element of document.querySelectorAll('.content-visibility-auto')) {
    observer.observe(element)
  }
}

(yes I'll unobserve everything beforeDestroy, this is just testing 😄)

They aren't massive pages, so removing it isn't a problem after the initial load.

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Awesome, making use of what we have for now.
Unfortionally it's a not stable function yet. I had this issue where it hides half my divs on my detail pages. :(

Thread Thread
 
marcellothearcane profile image
marcellothearcane

This version's a bit more stable: 5f6c7268798c4d000721ae4b--tillys-w...

I used the ResizeObserver above to work out an average height value for the contain-intrinsic-size too.

A fun project, thanks for sharing this css trick!

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

That seems really great!
Scrolls nice