Commit 2debe7fb authored by Kuba Juszczyk's avatar Kuba Juszczyk Committed by JJ Kasper

Allow opting out of automatic prefetch for Link (#7532)

* Restoring not working mouse event

* Restoring possibility of conditionally switching off the prefetch
parent 0af9d849
...@@ -53,9 +53,6 @@ type LinkProps = { ...@@ -53,9 +53,6 @@ type LinkProps = {
shallow?: boolean shallow?: boolean
passHref?: boolean passHref?: boolean
onError?: (error: Error) => void onError?: (error: Error) => void
/**
* @deprecated since version 8.1.1-canary.20
*/
prefetch?: boolean prefetch?: boolean
} }
...@@ -110,6 +107,10 @@ const listenToIntersections = (el: any, cb: any) => { ...@@ -110,6 +107,10 @@ const listenToIntersections = (el: any, cb: any) => {
class Link extends Component<LinkProps> { class Link extends Component<LinkProps> {
static propTypes?: any static propTypes?: any
static defaultProps: Partial<LinkProps> = {
prefetch: true,
}
cleanUpListeners = () => {} cleanUpListeners = () => {}
componentDidMount() { componentDidMount() {
...@@ -121,7 +122,7 @@ class Link extends Component<LinkProps> { ...@@ -121,7 +122,7 @@ class Link extends Component<LinkProps> {
} }
handleRef(ref: Element) { handleRef(ref: Element) {
if (IntersectionObserver && ref && ref.tagName) { if (this.props.prefetch && IntersectionObserver && ref && ref.tagName) {
this.cleanUpListeners = listenToIntersections(ref, () => { this.cleanUpListeners = listenToIntersections(ref, () => {
this.prefetch() this.prefetch()
}) })
...@@ -188,7 +189,7 @@ class Link extends Component<LinkProps> { ...@@ -188,7 +189,7 @@ class Link extends Component<LinkProps> {
} }
prefetch() { prefetch() {
if (typeof window === 'undefined') return if (!this.props.prefetch || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client) // Prefetch the JSON page if asked (only in the client)
const { pathname } = window.location const { pathname } = window.location
......
import Link from 'next/link'
export default () => (
<div>
<Link prefetch={false} href='/another'>
<a>I'm not pre-fetched..</a>
</Link>
</div>
)
...@@ -121,4 +121,21 @@ describe('Prefetching Links in viewport', () => { ...@@ -121,4 +121,21 @@ describe('Prefetching Links in viewport', () => {
if (browser) await browser.close() if (browser) await browser.close()
} }
}) })
it('should not prefetch when prefetch is explicitly set to false', async () => {
const browser = await webdriver(appPort, '/opt-out')
await waitFor(2 * 1000)
const links = await browser.elementsByCss('link[rel=preload]')
let found = false
for (const link of links) {
const href = await link.getAttribute('href')
if (href.includes('another')) {
found = true
break
}
}
expect(found).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