Gatsby: Disable prefetching on Link component

Created on 13 May 2019  路  4Comments  路  Source: gatsbyjs/gatsby

Summary

The Link component should have a prop in order to disable prefetching. Another option could be to prefetch only on mouse hover.

Basic example

<Link to="" noPrefetch />

Motivation

I have on my website (https://www.r眉n.run) lots of links. All the prefetching ruins my PageSpeed.

Most helpful comment

This should be the right snippet:

import React from 'react'
import { Link } from 'gatsby'
import { Link as RouterLink } from '@reach/router'

function MyLink({ children, to, prefetch, ...rest }) {
  if (!prefetch) {
    return <RouterLink to={to} {...rest}>{children}</RouterLink >
  }
  return <Link to={to} {...rest}>{children}</Link>
}

MyLink.defaultProps = {
  prefetch: true
}

export default MyLink

All 4 comments

This can and probably should live in user-land. There was a similar issue here that was closed with the following snippet.

import React from 'react'
import { Link } from 'gatsby'

function MyLink({ children, to, prefetch, ...rest }) {
  if (!prefetch) {
    return <a href={to} {...rest}>{children}</a>
  }
  return <Link to={to} {...rest}>{children}</Link>
}

MyLink.defaultProps = {
  prefetch: true
}

export default MyLink

Going to do the same here--if you feel differently, please feel free to reply and any of us are happy to discuss further.

Thanks!

This should be the right snippet:

import React from 'react'
import { Link } from 'gatsby'
import { Link as RouterLink } from '@reach/router'

function MyLink({ children, to, prefetch, ...rest }) {
  if (!prefetch) {
    return <RouterLink to={to} {...rest}>{children}</RouterLink >
  }
  return <Link to={to} {...rest}>{children}</Link>
}

MyLink.defaultProps = {
  prefetch: true
}

export default MyLink

@runes-tr Your solution causes my gatsby links to 404. Do you know how to fix this?

Was this page helpful?
0 / 5 - 0 ratings