Unverified Commit c8fa2848 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Control <Image /> prefetching with React (#18904)

This pull request fixes `<Image />` not updating when new props are passed by removing external DOM mutations and relying on React to do it instead.

As an added bonus, I've extracted the intersection observer from both the `<Image />` and `<Link />` component, as their instance can be shared!

The increase in size is minor (+3B), and actually a decrease for apps using both `<Image />` and `<Link />`.

---

Fixes #18698
Fixes #18369
parent 37fb0ad2
import React, { ReactElement, useEffect, useRef } from 'react' import React, { ReactElement } from 'react'
import Head from '../next-server/lib/head' import Head from '../next-server/lib/head'
import { useIntersection } from './use-intersection'
const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const const VALID_LOADING_VALUES = ['lazy', 'eager', undefined] as const
type LoadingValue = typeof VALID_LOADING_VALUES[number] type LoadingValue = typeof VALID_LOADING_VALUES[number]
...@@ -71,45 +72,6 @@ const allSizes = [...configDeviceSizes, ...configImageSizes] ...@@ -71,45 +72,6 @@ const allSizes = [...configDeviceSizes, ...configImageSizes]
configDeviceSizes.sort((a, b) => a - b) configDeviceSizes.sort((a, b) => a - b)
allSizes.sort((a, b) => a - b) allSizes.sort((a, b) => a - b)
let cachedObserver: IntersectionObserver
function getObserver(): IntersectionObserver | undefined {
const IntersectionObserver =
typeof window !== 'undefined' ? window.IntersectionObserver : null
// Return shared instance of IntersectionObserver if already created
if (cachedObserver) {
return cachedObserver
}
// Only create shared IntersectionObserver if supported in browser
if (!IntersectionObserver) {
return undefined
}
return (cachedObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
let lazyImage = entry.target as HTMLImageElement
unLazifyImage(lazyImage)
cachedObserver.unobserve(lazyImage)
}
})
},
{ rootMargin: '200px' }
))
}
function unLazifyImage(lazyImage: HTMLImageElement): void {
if (lazyImage.dataset.src) {
lazyImage.src = lazyImage.dataset.src
}
if (lazyImage.dataset.srcset) {
lazyImage.srcset = lazyImage.dataset.srcset
}
lazyImage.style.visibility = 'visible'
lazyImage.classList.remove('__lazy')
}
function getSizes( function getSizes(
width: number | undefined, width: number | undefined,
layout: LayoutValue layout: LayoutValue
...@@ -255,8 +217,6 @@ export default function Image({ ...@@ -255,8 +217,6 @@ export default function Image({
objectPosition, objectPosition,
...all ...all
}: ImageProps) { }: ImageProps) {
const thisEl = useRef<HTMLImageElement>(null)
let rest: Partial<ImageProps> = all let rest: Partial<ImageProps> = all
let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic' let layout: NonNullable<LayoutValue> = sizes ? 'responsive' : 'intrinsic'
let unsized = false let unsized = false
...@@ -306,33 +266,19 @@ export default function Image({ ...@@ -306,33 +266,19 @@ export default function Image({
} }
} }
let lazy = loading === 'lazy' let isLazy =
if (!priority && typeof loading === 'undefined') { !priority && (loading === 'lazy' || typeof loading === 'undefined')
lazy = true
}
if (src && src.startsWith('data:')) { if (src && src.startsWith('data:')) {
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
unoptimized = true unoptimized = true
lazy = false isLazy = false
} }
useEffect(() => { const [setRef, isIntersected] = useIntersection<HTMLImageElement>({
const target = thisEl.current rootMargin: '200px',
if (target) { disabled: !isLazy,
const observer = lazy && getObserver() })
const isVisible = !isLazy || isIntersected
if (observer) {
observer.observe(target)
return () => {
observer.unobserve(target)
}
} else {
unLazifyImage(target)
}
}
}, [thisEl, lazy])
const widthInt = getInt(width) const widthInt = getInt(width)
const heightInt = getInt(height) const heightInt = getInt(height)
...@@ -342,7 +288,7 @@ export default function Image({ ...@@ -342,7 +288,7 @@ export default function Image({
let sizerStyle: JSX.IntrinsicElements['div']['style'] | undefined let sizerStyle: JSX.IntrinsicElements['div']['style'] | undefined
let sizerSvg: string | undefined let sizerSvg: string | undefined
let imgStyle: ImgElementStyle | undefined = { let imgStyle: ImgElementStyle | undefined = {
visibility: lazy ? 'hidden' : 'visible', visibility: isVisible ? 'visible' : 'hidden',
position: 'absolute', position: 'absolute',
top: 0, top: 0,
...@@ -451,29 +397,16 @@ export default function Image({ ...@@ -451,29 +397,16 @@ export default function Image({
}) })
let imgAttributes: let imgAttributes:
| { | Pick<JSX.IntrinsicElements['img'], 'src' | 'srcSet'>
src: string | undefined
srcSet?: string
} if (isVisible) {
| {
'data-src': string
'data-srcset'?: string
}
if (!lazy) {
imgAttributes = { imgAttributes = {
src: imgSrc, src: imgSrc,
} }
if (imgSrcSet) { if (imgSrcSet) {
imgAttributes.srcSet = imgSrcSet imgAttributes.srcSet = imgSrcSet
} }
} else {
imgAttributes = {
'data-src': imgSrc,
}
if (imgSrcSet) {
imgAttributes['data-srcset'] = imgSrcSet
}
className = className ? className + ' __lazy' : '__lazy'
} }
// No need to add preloads on the client side--by the time the application is hydrated, // No need to add preloads on the client side--by the time the application is hydrated,
...@@ -516,7 +449,7 @@ export default function Image({ ...@@ -516,7 +449,7 @@ export default function Image({
decoding="async" decoding="async"
className={className} className={className}
sizes={sizes} sizes={sizes}
ref={thisEl} ref={setRef}
style={imgStyle} style={imgStyle}
/> />
</div> </div>
......
import React, { Children } from 'react' import React, { Children, useEffect } from 'react'
import { UrlObject } from 'url' import { UrlObject } from 'url'
import { import {
addBasePath, addBasePath,
...@@ -9,6 +9,7 @@ import { ...@@ -9,6 +9,7 @@ import {
resolveHref, resolveHref,
} from '../next-server/lib/router/router' } from '../next-server/lib/router/router'
import { useRouter } from './router' import { useRouter } from './router'
import { useIntersection } from './use-intersection'
type Url = string | UrlObject type Url = string | UrlObject
type RequiredKeys<T> = { type RequiredKeys<T> = {
...@@ -31,60 +32,8 @@ export type LinkProps = { ...@@ -31,60 +32,8 @@ export type LinkProps = {
type LinkPropsRequired = RequiredKeys<LinkProps> type LinkPropsRequired = RequiredKeys<LinkProps>
type LinkPropsOptional = OptionalKeys<LinkProps> type LinkPropsOptional = OptionalKeys<LinkProps>
let cachedObserver: IntersectionObserver
const listeners = new Map<Element, () => void>()
const IntersectionObserver =
typeof window !== 'undefined' ? window.IntersectionObserver : null
const prefetched: { [cacheKey: string]: boolean } = {} const prefetched: { [cacheKey: string]: boolean } = {}
function getObserver(): IntersectionObserver | undefined {
// Return shared instance of IntersectionObserver if already created
if (cachedObserver) {
return cachedObserver
}
// Only create shared IntersectionObserver if supported in browser
if (!IntersectionObserver) {
return undefined
}
return (cachedObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (!listeners.has(entry.target)) {
return
}
const cb = listeners.get(entry.target)!
if (entry.isIntersecting || entry.intersectionRatio > 0) {
cachedObserver.unobserve(entry.target)
listeners.delete(entry.target)
cb()
}
})
},
{ rootMargin: '200px' }
))
}
const listenToIntersections = (el: Element, cb: () => void) => {
const observer = getObserver()
if (!observer) {
return () => {}
}
observer.observe(el)
listeners.set(el, cb)
return () => {
try {
observer.unobserve(el)
} catch (err) {
console.error(err)
}
listeners.delete(el)
}
}
function prefetch( function prefetch(
router: NextRouter, router: NextRouter,
href: string, href: string,
...@@ -285,30 +234,12 @@ function Link(props: React.PropsWithChildren<LinkProps>) { ...@@ -285,30 +234,12 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
const child: any = Children.only(children) const child: any = Children.only(children)
const childRef: any = child && typeof child === 'object' && child.ref const childRef: any = child && typeof child === 'object' && child.ref
const cleanup = React.useRef<() => void>() const [setIntersectionRef, isVisible] = useIntersection({
rootMargin: '200px',
})
const setRef = React.useCallback( const setRef = React.useCallback(
(el: Element) => { (el: Element) => {
// cleanup previous event handlers setIntersectionRef(el)
if (cleanup.current) {
cleanup.current()
cleanup.current = undefined
}
if (p && IntersectionObserver && el && el.tagName && isLocalURL(href)) {
// Join on an invalid URI character
const isPrefetched = prefetched[href + '%' + as]
if (!isPrefetched) {
cleanup.current = listenToIntersections(el, () => {
prefetch(router, href, as, {
locale:
typeof locale !== 'undefined'
? locale
: router && router.locale,
})
})
}
}
if (childRef) { if (childRef) {
if (typeof childRef === 'function') childRef(el) if (typeof childRef === 'function') childRef(el)
else if (typeof childRef === 'object') { else if (typeof childRef === 'object') {
...@@ -316,8 +247,18 @@ function Link(props: React.PropsWithChildren<LinkProps>) { ...@@ -316,8 +247,18 @@ function Link(props: React.PropsWithChildren<LinkProps>) {
} }
} }
}, },
[p, childRef, href, as, router, locale] [childRef, setIntersectionRef]
) )
useEffect(() => {
const shouldPrefetch = isVisible && p && isLocalURL(href)
const isPrefetched = prefetched[href + '%' + as]
if (shouldPrefetch && !isPrefetched) {
prefetch(router, href, as, {
locale:
typeof locale !== 'undefined' ? locale : router && router.locale,
})
}
}, [as, href, isVisible, locale, p, router])
const childProps: { const childProps: {
onMouseEnter?: React.MouseEventHandler onMouseEnter?: React.MouseEventHandler
......
import { useCallback, useEffect, useRef, useState } from 'react'
type UseIntersectionObserverInit = Pick<IntersectionObserverInit, 'rootMargin'>
type UseIntersection = { disabled?: boolean } & UseIntersectionObserverInit
type ObserveCallback = (isVisible: boolean) => void
const hasIntersectionObserver = typeof IntersectionObserver !== 'undefined'
export function useIntersection<T extends Element>({
rootMargin,
disabled,
}: UseIntersection): [(element: T | null) => void, boolean] {
const isDisabled = disabled || !hasIntersectionObserver
const unobserve = useRef<Function>()
const [visible, setVisible] = useState(false)
const setRef = useCallback(
(el: T | null) => {
if (unobserve.current) {
unobserve.current()
unobserve.current = undefined
}
if (isDisabled || visible) return
if (el && el.tagName) {
unobserve.current = observe(
el,
(isVisible) => isVisible && setVisible(isVisible),
{ rootMargin }
)
}
},
[isDisabled, rootMargin, visible]
)
useEffect(() => {
if (!hasIntersectionObserver) {
if (!visible) setVisible(true)
}
}, [visible])
return [setRef, visible]
}
function observe(
element: Element,
callback: ObserveCallback,
options: UseIntersectionObserverInit
) {
const { id, observer, elements } = createObserver(options)
elements.set(element, callback)
observer.observe(element)
return function unobserve() {
observer.unobserve(element)
// Destroy observer when there's nothing left to watch:
if (elements.size === 0) {
observer.disconnect()
observers.delete(id)
}
}
}
const observers = new Map<
string,
{
id: string
observer: IntersectionObserver
elements: Map<Element, ObserveCallback>
}
>()
function createObserver(options: UseIntersectionObserverInit) {
const id = options.rootMargin || ''
let instance = observers.get(id)
if (instance) {
return instance
}
const elements = new Map<Element, ObserveCallback>()
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
const callback = elements.get(entry.target)
const isVisible = entry.isIntersecting || entry.intersectionRatio > 0
if (callback && isVisible) {
callback(isVisible)
}
})
}, options)
observers.set(
id,
(instance = {
id,
observer,
elements,
})
)
return instance
}
...@@ -106,7 +106,7 @@ function lazyLoadingTests() { ...@@ -106,7 +106,7 @@ function lazyLoadingTests() {
}) })
it('should pass through classes on a lazy loaded image', async () => { it('should pass through classes on a lazy loaded image', async () => {
expect(await browser.elementById('lazy-mid').getAttribute('class')).toBe( expect(await browser.elementById('lazy-mid').getAttribute('class')).toBe(
'exampleclass __lazy' 'exampleclass'
) )
}) })
it('should load the second image after scrolling down', async () => { it('should load the second image after scrolling down', async () => {
......
import React, { useState } from 'react'
import Image from 'next/image'
const Page = () => {
const [toggled, setToggled] = useState(false)
return (
<div>
<p>Update Page</p>
<Image
id="update-image"
src={toggled ? '/test.png' : '/test.jpg'}
width="400"
height="400"
></Image>
<p id="stubtext">This is the index page</p>
<button id="toggle" onClick={() => setToggled(true)}>
Toggle
</button>
</div>
)
}
export default Page
...@@ -90,6 +90,29 @@ function runTests(mode) { ...@@ -90,6 +90,29 @@ function runTests(mode) {
} }
}) })
it('should update the image on src change', async () => {
let browser
try {
browser = await webdriver(appPort, '/update')
await check(
() => browser.eval(`document.getElementById("update-image").src`),
/test\.jpg/
)
await browser.eval(`document.getElementById("toggle").click()`)
await check(
() => browser.eval(`document.getElementById("update-image").src`),
/test\.png/
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work when using flexbox', async () => { it('should work when using flexbox', async () => {
let browser let browser
try { try {
......
...@@ -80,7 +80,7 @@ describe('Production response size', () => { ...@@ -80,7 +80,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizesBytes - 281 * 1024 const delta = responseSizesBytes - 282 * 1024
expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb expect(delta).toBeLessThanOrEqual(1024) // don't increase size more than 1kb
expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target expect(delta).toBeGreaterThanOrEqual(-1024) // don't decrease size more than 1kb without updating target
}) })
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment