Skip to content

Commit

Permalink
Make the image post-processor ignore SVG images (vercel#16732)
Browse files Browse the repository at this point in the history
This is a small change to the image post-processor logic. When it's looking for images to preload, it will now ignore SVGs, as these are rarely the relevant images for LCP.
  • Loading branch information
atcastle authored and Piotr Bosak committed Sep 26, 2020
1 parent a250ded commit 393f15a
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/next/next-server/lib/post-process.ts
Expand Up @@ -191,8 +191,10 @@ class ImageOptimizerMiddleware implements PostProcessMiddleware {
}

function isImgEligible(imgElement: HTMLElement): boolean {
let imgSrc = imgElement.getAttribute('src')
return (
imgElement.hasAttribute('src') &&
!!imgSrc &&
sourceIsSupportedType(imgSrc) &&
imageIsNotTooSmall(imgElement) &&
imageIsNotHidden(imgElement)
)
Expand Down Expand Up @@ -243,6 +245,11 @@ function imageIsNotHidden(imgElement: HTMLElement): boolean {
return true
}

// Currently only filters out svg images--could be made more specific in the future.
function sourceIsSupportedType(imgSrc: string): boolean {
return !imgSrc.includes('.svg')
}

// Initialization
registerPostProcessor(
'Inline-Fonts',
Expand Down
1 change: 1 addition & 0 deletions test/integration/image-optimization/pages/index.js
Expand Up @@ -6,6 +6,7 @@ const Page = () => {
<link rel="preload" href="already-preloaded.jpg" />
<img src="already-preloaded.jpg" />
<img src="tiny-image.jpg" width="20" height="20" />
<img src="vector-image.svg" />
<img src="hidden-image-1.jpg" hidden />
<div hidden>
<img src="hidden-image-2.jpg" />
Expand Down
1 change: 1 addition & 0 deletions test/integration/image-optimization/pages/stars.js
Expand Up @@ -6,6 +6,7 @@ function Home({ stars }) {
<link rel="preload" href="already-preloaded.jpg" />
<img src="already-preloaded.jpg" />
<img src="tiny-image.jpg" width="20" height="20" />
<img src="vector-image.svg" />
<img src="hidden-image-1.jpg" hidden />
<div hidden>
<img src="hidden-image-2.jpg" />
Expand Down
6 changes: 6 additions & 0 deletions test/integration/image-optimization/test/index.test.js
Expand Up @@ -53,6 +53,12 @@ function checkImagesOnPage(path) {
'<link rel="preload" href="hidden-image-2.jpg" as="image"/>'
)
})
it('should not preload SVG images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).not.toContain(
'<link rel="preload" href="vector-image.svg" as="image"/>'
)
})
it('should preload exactly two eligible images', async () => {
const html = await renderViaHTTP(appPort, path)
expect(html).toContain(
Expand Down

0 comments on commit 393f15a

Please sign in to comment.