Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix next/image being downloaded multiple times on Safari #22902

Merged
merged 3 commits into from
Mar 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion packages/next/client/image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,6 @@ function generateImgAttrs({
const last = widths.length - 1

return {
src: loader({ src, quality, width: widths[last] }),
sizes: !sizes && kind === 'w' ? '100vw' : sizes,
srcSet: widths
.map(
Expand All @@ -177,6 +176,14 @@ function generateImgAttrs({
}${kind}`
)
.join(', '),

// It's intended to keep `src` the last attribute because React updates
// attributes in order. If we keep `src` the first one, Safari will
// immediately start to fetch `src`, before `sizes` and `srcSet` are even
// updated by React. That causes multiple unnecessary requests if `srcSet`
// and `sizes` are defined.
// This bug cannot be reproduced in Chrome or Firefox.
src: loader({ src, quality, width: widths[last] }),
}
}

Expand Down
7 changes: 7 additions & 0 deletions test/integration/image-component/basic/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ const Page = () => {
return (
<div>
<p>Hello World</p>
<Image
id="image-with-sizes"
src="/test-sizes.jpg"
width={2000}
height={100}
sizes="100vw"
/>
<Image
id="basic-image"
src="foo.jpg"
Expand Down
12 changes: 12 additions & 0 deletions test/integration/image-component/basic/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,18 @@ describe('Image Component Tests', () => {
)
).toBe(false)
})
it('should only be loaded once if `sizes` is set', async () => {
// Get all network requests
const resourceEntries = await browser.eval(
'window.performance.getEntries()'
)

// "test-sizes.jpg" should only occur once
const requests = resourceEntries.filter((entry) =>
entry.name.includes('test-sizes.jpg')
)
expect(requests.length).toBe(1)
})
describe('Client-side Errors', () => {
beforeAll(async () => {
await browser.eval(`(function() {
Expand Down