Skip to content

Instantly share code, notes, and snippets.

@marekpiechut
Last active July 3, 2020 11:56
Show Gist options
  • Select an option

  • Save marekpiechut/24416c82dcb6858f47cd54b66b5a8665 to your computer and use it in GitHub Desktop.

Select an option

Save marekpiechut/24416c82dcb6858f47cd54b66b5a8665 to your computer and use it in GitHub Desktop.
Get lazy loading cheap with intersectionobserver i ccc4a072ab24457ea3de05cd8ed8f5ed
const useLazyMediaLoad = media => {
const [url, setUrl] = useState<?string>(null)
const targetRef = useRef<?HTMLElement>(null)
useEffect(() => {
if (!IntersectionObserver) {
thumbLoader(media).then(setUrl)
} else if (targetRef.current) {
let observer = new IntersectionObserver(
entries =>
entries.forEach(entry => {
if (entry.isIntersecting) {
thumbLoader(media).then(setUrl)
observer = observer.disconnect()
}
}),
{ rootMargin: '0px 0px 200px 0px' }
)
observer.observe(targetRef.current)
return () => (observer = observer && observer.disconnect())
}
}, [media])
return [url, targetRef]
}
const ExerciseItem = ({ exercise }: Props) => {
const [url, targetRef] = useLazyMediaLoad(exercise.media)
return (
<div
css={styles.thumb}
style={{ backgroundImage: url ? `url(${url})` : MISSING_VIDEO }}
ref={targetRef}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment