Skip to content

Commit

Permalink
Fix PerformanceObserver usage for older browsers and CI (#30387)
Browse files Browse the repository at this point in the history
Browsers older than 2017 don't have PerformanceObserver https://caniuse.com/mdn-api_performanceobserver


- Fixes #30322
- Fixes https://twitter.com/fmgordillo/status/1453037730141716492
  • Loading branch information
styfle authored Oct 27, 2021
1 parent 89e244e commit 3bdf80d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 10 deletions.
10 changes: 1 addition & 9 deletions docs/basic-features/image-optimization.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,7 @@ Loaders can be defined per-image, or at the application level.

You should add the `priority` property to the image that will be the [Largest Contentful Paint (LCP) element](https://web.dev/lcp/#what-elements-are-considered) for each page. Doing so allows Next.js to specially prioritize the image for loading (e.g. through preload tags or priority hints), leading to a meaningful boost in LCP.

The LCP element is typically the largest image or text block visible within the viewport of the page. You can verify which element this is by running the following code in the console of your page and looking at the latest result:

```javascript
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
console.log('LCP candidate:', entry.startTime, entry.element)
}
}).observe({ type: 'largest-contentful-paint', buffered: true })
```
The LCP element is typically the largest image or text block visible within the viewport of the page. When you run `next dev`, you'll see a console warning if the LCP element is an `<Image>` without the `priority` property.

Once you've identified the LCP image, you can add the property like this:

Expand Down
6 changes: 5 additions & 1 deletion packages/next/client/image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,11 @@ export default function Image({
)
}

if (typeof window !== 'undefined' && !perfObserver) {
if (
typeof window !== 'undefined' &&
!perfObserver &&
window.PerformanceObserver
) {
perfObserver = new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
// @ts-ignore - missing "LargestContentfulPaint" class with "element" prop
Expand Down

0 comments on commit 3bdf80d

Please sign in to comment.