Unverified Commit 0cf373a5 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

add flag to opt into smooth scroll detection & add warning (#81563)

**What:**
`layout-router` currently forces style recalculation on every navigation by manipulating the `scroll-behavior` CSS property on the `<html>` element. This would impact most navigations, even though most don't use smooth scrolling

**Why:**
To prevent smooth scrolling during router navigation (which can feel janky), Next.js temporarily resets `scroll-behavior` to `auto`, then restores the original value (#40642). While this solves the UX issue, it causes performance overhead for the vast majority of users who don't have smooth scrolling configured.

**How:**
This PR introduces an optimization that checks for a `data-scroll-behavior="smooth"` attribute before manipulating styles. Only users who explicitly opt into smooth scrolling will experience the style recalculation.

- The existing behavior is preserved by default
- Opt-in to the new behavior by setting `experimental.optimizeRouterScrolling: true` in Next.js config
- When smooth-scroll is detected on the document, a development warning is logged to notify that the default behavior will be changing in an upcoming major.
parent 9a6f1bd4
---
title: 'Missing data-scroll-behavior Attribute for Smooth Scroll'
---
## Why This Warning Occurred
Your application has smooth scrolling enabled via CSS (`scroll-behavior: smooth`), but you haven't added the `data-scroll-behavior="smooth"` attribute to your `<html>` element.
Next.js automatically attempts to detect the smooth scrolling configuration to ensure that navigating back/forward through the router doesn't also trigger the smooth scrolling behavior, as this is often not desired.
In a future version of Next.js, this behavior will no longer be automatically detected, and you will need to add the `data-scroll-behavior` attribute to your `<html>` element to opt-in to having Next.js disable smooth scrolling during route transitions.
## Possible Ways to Fix It
Add `data-scroll-behavior="smooth"` to your `<html>` element to prepare for the upcoming optimization:
```html filename="app/layout.tsx"
export default function RootLayout({ children, }: { children: React.ReactNode })
{ return (
<html lang="en" data-scroll-behavior="smooth">
<body>
{children}
</body>
</html>
) }
```
Or if you're using the Pages Router:
```html filename="pages/_document.tsx"
import { Html, Head, Main, NextScript } from 'next/document' export default
function Document() { return (
<html lang="en" data-scroll-behavior="smooth">
<head />
<body>
<main />
<NextScript />
</body>
</html>
) }
```
## Why This Optimization Matters
Without the data attribute, Next.js must modify the `scroll-behavior` style on the `<html>` element on every navigation to ensure smooth scrolling isn't triggered. This can cause unnecessary style recalculation and impact performance.
With the data attribute, Next.js can instantly detect smooth scrolling configuration without triggering style recalculation, resulting in faster navigation and making this behavior opt-in.
## Enabling the Optimization Early
You can enable this optimization early by adding the experimental flag to your `next.config.js`:
```js filename="next.config.js"
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
optimizeRouterScrolling: true,
},
}
module.exports = nextConfig
```
...@@ -339,6 +339,8 @@ export function getDefineEnv({ ...@@ -339,6 +339,8 @@ export function getDefineEnv({
// no-op that just restarts the development server. // no-op that just restarts the development server.
'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE': 'process.env.__NEXT_BUNDLER_HAS_PERSISTENT_CACHE':
!isTurbopack || (config.experimental.turbopackPersistentCaching ?? false), !isTurbopack || (config.experimental.turbopackPersistentCaching ?? false),
'process.env.__NEXT_OPTIMIZE_ROUTER_SCROLL':
config.experimental.optimizeRouterScrolling ?? false,
} }
const userDefines = config.compiler?.define ?? {} const userDefines = config.compiler?.define ?? {}
......
...@@ -512,6 +512,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -512,6 +512,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
}), }),
]) ])
.optional(), .optional(),
optimizeRouterScrolling: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -768,6 +768,15 @@ export interface ExperimentalConfig { ...@@ -768,6 +768,15 @@ export interface ExperimentalConfig {
*/ */
showSourceLocation?: boolean showSourceLocation?: boolean
} }
/**
* When enabled, will only opt-in to special smooth scroll handling when
* data-scroll-behavior="smooth" is present on the <html> element.
* This will be the default, non-configurable behavior in the next major version.
*
* @default false
*/
optimizeRouterScrolling?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
...@@ -1490,6 +1499,7 @@ export const defaultConfig = { ...@@ -1490,6 +1499,7 @@ export const defaultConfig = {
devtoolNewPanelUI: process.env.__NEXT_DEVTOOL_NEW_PANEL_UI === 'true', devtoolNewPanelUI: process.env.__NEXT_DEVTOOL_NEW_PANEL_UI === 'true',
devtoolSegmentExplorer: process.env.__NEXT_DEVTOOL_NEW_PANEL_UI === 'true', devtoolSegmentExplorer: process.env.__NEXT_DEVTOOL_NEW_PANEL_UI === 'true',
browserDebugInfoInTerminal: false, browserDebugInfoInTerminal: false,
optimizeRouterScrolling: false,
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
......
import { warnOnce } from '../../utils/warn-once'
/** /**
* Run function with `scroll-behavior: auto` applied to `<html/>`. * Run function with `scroll-behavior: auto` applied to `<html/>`.
* This css change will be reverted after the function finishes. * This css change will be reverted after the function finishes.
...@@ -12,7 +14,38 @@ export function disableSmoothScrollDuringRouteTransition( ...@@ -12,7 +14,38 @@ export function disableSmoothScrollDuringRouteTransition(
fn() fn()
return return
} }
const htmlElement = document.documentElement const htmlElement = document.documentElement
const hasDataAttribute = htmlElement.dataset.scrollBehavior === 'smooth'
// Since this is a breaking change, this is temporarily flagged
// and will be false by default.
// In the next major (v16), this will be automatically enabled
if (process.env.__NEXT_OPTIMIZE_ROUTER_SCROLL) {
if (!hasDataAttribute) {
// No smooth scrolling configured, run directly without style manipulation
fn()
return
}
} else {
// Old behavior: always manipulate styles, but warn about upcoming change
// Warn if smooth scrolling is detected but no data attribute is present
if (
process.env.NODE_ENV === 'development' &&
!hasDataAttribute &&
getComputedStyle(htmlElement).scrollBehavior === 'smooth'
) {
warnOnce(
'Detected `scroll-behavior: smooth` on the `<html>` element. In a future version, ' +
'Next.js will no longer automatically disable smooth scrolling during route transitions. ' +
'To prepare for this change, add `data-scroll-behavior="smooth"` to your <html> element. ' +
'Learn more: https://nextjs.org/docs/messages/missing-data-scroll-behavior'
)
}
}
// Proceed with temporarily disabling smooth scrolling
const existing = htmlElement.style.scrollBehavior const existing = htmlElement.style.scrollBehavior
htmlElement.style.scrollBehavior = 'auto' htmlElement.style.scrollBehavior = 'auto'
if (!options.dontForceLayout) { if (!options.dontForceLayout) {
......
html {
scroll-behavior: smooth;
}
body {
margin: 0;
height: 300vh; /* Make it very scrollable */
min-height: 2000px; /* Ensure minimum height for scrolling */
}
import React from 'react'
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html data-scroll-behavior="smooth">
<head></head>
<body>{children}</body>
</html>
)
}
import React from 'react'
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Smooth Scroll Optimization Tests</h1>
<div style={{ marginBottom: '20px' }}>
<Link
href="/optimized/page1"
style={{ display: 'block', marginBottom: '10px' }}
>
Test Optimized Smooth Scroll (with data attribute)
</Link>
<Link href="/legacy/page1" style={{ display: 'block' }}>
Test Legacy Smooth Scroll (no data attribute)
</Link>
</div>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page1() {
return (
<div>
<h1>Legacy Page 1</h1>
<p>This page has smooth scroll without data attribute optimization.</p>
<Link
href="/page2"
id="to-page2"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 2
</Link>
<div style={{ height: '150vh', backgroundColor: '#f0f0f0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 1</p>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page2() {
return (
<div>
<h1>Legacy Page 2</h1>
<p>This is the second page with legacy smooth scroll behavior.</p>
<Link
href="/page1"
id="to-page1"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 1
</Link>
<div style={{ height: '150vh', backgroundColor: '#e0e0e0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 2</p>
</div>
)
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
height: 300vh; /* Make it very scrollable */
min-height: 2000px; /* Ensure minimum height for scrolling */
}
import React from 'react'
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
import React from 'react'
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Smooth Scroll Optimization Tests</h1>
<div style={{ marginBottom: '20px' }}>
<Link
href="/optimized/page1"
style={{ display: 'block', marginBottom: '10px' }}
>
Test Optimized Smooth Scroll (with data attribute)
</Link>
<Link href="/legacy/page1" style={{ display: 'block' }}>
Test Legacy Smooth Scroll (no data attribute)
</Link>
</div>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page1() {
return (
<div>
<h1>Legacy Page 1</h1>
<p>This page has smooth scroll without data attribute optimization.</p>
<Link
href="/page2"
id="to-page2"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 2
</Link>
<div style={{ height: '150vh', backgroundColor: '#f0f0f0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 1</p>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page2() {
return (
<div>
<h1>Legacy Page 2</h1>
<p>This is the second page with legacy smooth scroll behavior.</p>
<Link
href="/page1"
id="to-page1"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 1
</Link>
<div style={{ height: '150vh', backgroundColor: '#e0e0e0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 2</p>
</div>
)
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
height: 300vh; /* Make it very scrollable */
min-height: 2000px; /* Ensure minimum height for scrolling */
}
import React from 'react'
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<head></head>
<body>{children}</body>
</html>
)
}
import React from 'react'
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Smooth Scroll Optimization Tests</h1>
<div style={{ marginBottom: '20px' }}>
<Link
href="/optimized/page1"
style={{ display: 'block', marginBottom: '10px' }}
>
Test Optimized Smooth Scroll (with data attribute)
</Link>
<Link href="/legacy/page1" style={{ display: 'block' }}>
Test Legacy Smooth Scroll (no data attribute)
</Link>
</div>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page1() {
return (
<div>
<h1>Optimized Page 1</h1>
<p>This page has smooth scroll with data attribute optimization.</p>
<Link
href="/page2"
id="to-page2"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 2
</Link>
<div style={{ height: '150vh', backgroundColor: '#f0f0f0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 1</p>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page2() {
return (
<div>
<h1>Optimized Page 2</h1>
<p>This is the second page with smooth scroll optimization.</p>
<Link
href="/page1"
id="to-page1"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 1
</Link>
<div style={{ height: '150vh', backgroundColor: '#e0e0e0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 2</p>
</div>
)
}
html {
scroll-behavior: smooth;
}
body {
margin: 0;
height: 300vh; /* Make it very scrollable */
min-height: 2000px; /* Ensure minimum height for scrolling */
}
import React from 'react'
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html data-scroll-behavior="smooth">
<head></head>
<body>{children}</body>
</html>
)
}
import React from 'react'
import Link from 'next/link'
export default function HomePage() {
return (
<div>
<h1>Smooth Scroll Optimization Tests</h1>
<div style={{ marginBottom: '20px' }}>
<Link
href="/optimized/page1"
style={{ display: 'block', marginBottom: '10px' }}
>
Test Optimized Smooth Scroll (with data attribute)
</Link>
<Link href="/legacy/page1" style={{ display: 'block' }}>
Test Legacy Smooth Scroll (no data attribute)
</Link>
</div>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page1() {
return (
<div>
<h1>Optimized Page 1</h1>
<p>This page has smooth scroll with data attribute optimization.</p>
<Link
href="/page2"
id="to-page2"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 2
</Link>
<div style={{ height: '150vh', backgroundColor: '#f0f0f0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 1</p>
</div>
)
}
import React from 'react'
import Link from 'next/link'
export default function Page2() {
return (
<div>
<h1>Optimized Page 2</h1>
<p>This is the second page with smooth scroll optimization.</p>
<Link
href="/page1"
id="to-page1"
style={{ display: 'block', marginBottom: '20px' }}
>
Go to Page 1
</Link>
<div style={{ height: '150vh', backgroundColor: '#e0e0e0' }}>
<p>Scroll content...</p>
<div style={{ height: '1000px' }} />
<p>More content...</p>
</div>
<p>Bottom of page 2</p>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('router smooth scroll optimization (legacy)', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname + '/fixtures/legacy',
nextConfig: {
experimental: {
optimizeRouterScrolling: false,
},
},
})
const getTopScroll = async (browser: any) =>
await browser.eval('document.documentElement.scrollTop')
const waitForScrollToComplete = async (browser: any, expectedY: number) => {
await retry(async () => {
const top = await getTopScroll(browser)
expect(top).toBe(expectedY)
})
}
const scrollTo = async (browser: any, y: number) => {
await browser.eval(`window.scrollTo(0, ${y})`)
// Add a small delay for scroll to complete
await browser.eval('new Promise(resolve => setTimeout(resolve, 100))')
await waitForScrollToComplete(browser, y)
}
it('should work with smooth scroll CSS and warn in development', async () => {
const browser = await next.browser('/page1')
await scrollTo(browser, 1000)
expect(await getTopScroll(browser)).toBe(1000)
// Wait for page to be rendered
await browser.waitForElementByCss('#to-page2')
// Click navigation and wait for new page to load
await browser.elementByCss('#to-page2').click()
// Wait for the new page to load completely
await browser.waitForElementByCss('h1')
await retry(async () => {
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Legacy Page 2')
})
await waitForScrollToComplete(browser, 0)
// In legacy mode, all smooth scroll usage should warn in dev mode
await retry(async () => {
const logs = await browser.log()
const hasWarning = logs.some((log) =>
log.message.includes(
'Detected `scroll-behavior: smooth` on the `<html>` element. In a future version'
)
)
if (isNextDev) {
expect(hasWarning).toBe(true)
} else {
expect(hasWarning).toBe(false)
}
})
})
})
describe('router smooth scroll optimization (legacy with data attribute)', () => {
const { next, isNextDev: _isNextDev } = nextTestSetup({
files: __dirname + '/fixtures/legacy-with-data',
nextConfig: {
experimental: {
optimizeRouterScrolling: false,
},
},
})
const getTopScroll = async (browser: any) =>
await browser.eval('document.documentElement.scrollTop')
const waitForScrollToComplete = async (browser: any, expectedY: number) => {
await retry(async () => {
const top = await getTopScroll(browser)
expect(top).toBe(expectedY)
})
}
const scrollTo = async (browser: any, y: number) => {
await browser.eval(`window.scrollTo(0, ${y})`)
// Add a small delay for scroll to complete
await browser.eval('new Promise(resolve => setTimeout(resolve, 100))')
await waitForScrollToComplete(browser, y)
}
it('should not warn when data attribute is present even in legacy mode', async () => {
const browser = await next.browser('/page1')
// Verify both CSS and data attribute are present
const scrollBehavior = await browser.eval(
'getComputedStyle(document.documentElement).scrollBehavior'
)
expect(scrollBehavior).toBe('smooth')
const hasDataAttribute = await browser.eval(
'document.documentElement.dataset.scrollBehavior === "smooth"'
)
expect(hasDataAttribute).toBe(true)
await scrollTo(browser, 1000)
expect(await getTopScroll(browser)).toBe(1000)
// Wait for page to be rendered
await browser.waitForElementByCss('#to-page2')
// Click navigation and wait for new page to load
await browser.elementByCss('#to-page2').click()
// Wait for the new page to load completely
await browser.waitForElementByCss('h1')
await retry(async () => {
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Legacy Page 2')
})
await waitForScrollToComplete(browser, 0)
// Both legacy and optimized modes respect the data attribute for warnings
// The difference is in when style manipulation occurs, not when warnings appear
await retry(async () => {
const logs = await browser.log()
const hasWarning = logs.some((log) =>
log.message.includes(
'Detected `scroll-behavior: smooth` on the `<html>` element. In a future version'
)
)
// No warning should appear when data attribute is present
expect(hasWarning).toBe(false)
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('router smooth scroll optimization (optimized)', () => {
const { next } = nextTestSetup({
files: __dirname + '/fixtures/optimized',
nextConfig: {
experimental: {
optimizeRouterScrolling: true,
},
},
})
const getTopScroll = async (browser: any) =>
await browser.eval('document.documentElement.scrollTop')
const waitForScrollToComplete = async (browser: any, expectedY: number) => {
await retry(async () => {
const top = await getTopScroll(browser)
expect(top).toBe(expectedY)
})
}
const scrollTo = async (browser: any, y: number) => {
await browser.eval(`window.scrollTo(0, ${y})`)
// Add a small delay for scroll to complete
await browser.eval('new Promise(resolve => setTimeout(resolve, 100))')
await waitForScrollToComplete(browser, y)
}
it('should work with smooth scroll CSS and data attribute without warning', async () => {
const browser = await next.browser('/page1')
await scrollTo(browser, 1000)
expect(await getTopScroll(browser)).toBe(1000)
// Wait for page to be rendered
await browser.waitForElementByCss('#to-page2')
// Click navigation and wait for new page to load
await browser.elementByCss('#to-page2').click()
// Wait for the new page to load completely
await browser.waitForElementByCss('h1')
await retry(async () => {
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Optimized Page 2')
})
await waitForScrollToComplete(browser, 0)
// Assert no warning appears in optimized case
await retry(async () => {
const logs = await browser.log()
expect(
logs.some((log) =>
log.message.includes(
'Detected `scroll-behavior: smooth` on the `<html>` element. In a future version'
)
)
).toBe(false)
})
})
})
describe('router smooth scroll optimization (optimized early exit)', () => {
const { next } = nextTestSetup({
files: __dirname + '/fixtures/optimized-no-data',
nextConfig: {
experimental: {
optimizeRouterScrolling: true,
},
},
})
const getTopScroll = async (browser: any) =>
await browser.eval('document.documentElement.scrollTop')
const waitForScrollToComplete = async (browser: any, expectedY: number) => {
await retry(async () => {
const top = await getTopScroll(browser)
expect(top).toBe(expectedY)
})
}
const scrollTo = async (browser: any, y: number) => {
await browser.eval(`window.scrollTo(0, ${y})`)
// Add a small delay for scroll to complete
await browser.eval('new Promise(resolve => setTimeout(resolve, 100))')
await waitForScrollToComplete(browser, y)
}
it('should exit early when CSS smooth scroll detected but no data attribute', async () => {
const browser = await next.browser('/page1')
// Verify CSS smooth scrolling is present
const scrollBehavior = await browser.eval(
'getComputedStyle(document.documentElement).scrollBehavior'
)
expect(scrollBehavior).toBe('smooth')
// Verify no data attribute
const hasDataAttribute = await browser.eval(
'document.documentElement.dataset.scrollBehavior === "smooth"'
)
expect(hasDataAttribute).toBe(false)
await scrollTo(browser, 1000)
expect(await getTopScroll(browser)).toBe(1000)
// Wait for page to be rendered
await browser.waitForElementByCss('#to-page2')
// Click navigation and wait for new page to load
await browser.elementByCss('#to-page2').click()
// Wait for the new page to load completely
await browser.waitForElementByCss('h1')
await retry(async () => {
const text = await browser.elementByCss('h1').text()
expect(text).toBe('Optimized Page 2')
})
await waitForScrollToComplete(browser, 0)
// No warning should appear in optimized mode even with CSS smooth scroll
// because the function exits early when no data attribute is present
await retry(async () => {
const logs = await browser.log()
expect(
logs.some((log) =>
log.message.includes(
'Detected `scroll-behavior: smooth` on the `<html>` element. In a future version'
)
)
).toBe(false)
})
})
})
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