Last active
July 3, 2020 11:56
-
-
Save marekpiechut/24416c82dcb6858f47cd54b66b5a8665 to your computer and use it in GitHub Desktop.
Get lazy loading cheap with intersectionobserver i ccc4a072ab24457ea3de05cd8ed8f5ed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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