data-prefetch-link icon indicating copy to clipboard operation
data-prefetch-link copied to clipboard

data-prefetch-link on hover

Open Enalmada opened this issue 6 years ago • 1 comments

The readme wisely states not to use data-prefetch-link on large lists so as a compromise I would like to do it when a user hovers a link. http://instantclick.io makes traditional sites feel so much faster because there is usually enough of a delay between user intent to click and actual click to start fetching data.

Apollo has an example of prefetching here: onMouseOver={() => client.query({ query: GET_DOG, variables: { breed: data.breed } }) }

...but the way they do it seems unmaintainable...every link has to know all queries onMouseOver needs for the target page. It seems much better to do what data-prefetch-link does but in onMouseOver and then the getInitialProps on a page can manage queries more locally...something like this:

if(isVirtualCall) { // from data-prefetch-link
        client.query(...)
}

Workaround from @adamsoffer ... Take a look at this: https://shaleenjain.com/blog/nextjs-apollo-prefetch/ You can create “prefetch()” function and invoke it on mouseOver.

import Router from 'next/router'
import { format, resolve, parse } from 'url'

export default prefetch = async (href) => {
  // if  we're running server side do nothing
  if (typeof window === 'undefined') return

  const url =
    typeof href !== 'string'
      ? format(href)
      : href

  const { pathname } = window.location

  const parsedHref = resolve(pathname, url)

  const { query } =
    typeof href !== 'string'
      ? href
      : parse(url, true);

  // get component reference
  const Component = await Router.prefetch(parsedHref)

  // fetch the component props
  // and cache locally, handled within getInitialProps
  if (Component && Component.getInitialProps) {
    const ctx = { pathname: href, query, isVirtualCall: true }
    await Component.getInitialProps(ctx)
  }
}

Any chance data-prefetch-link would support a hover enable parameter to speed up all those links you may not necessarily want prefetched on page load?

Enalmada avatar Nov 28 '18 18:11 Enalmada

I tried this and made it work, but the issue is when someone is clicking faster, so if prefetch on hover did not finish, it's invoking another one so you get double calls. I suppose there must be a method to stop fetch if the new one has been invoked but did not investigate further.

goranefbl avatar Jan 08 '19 08:01 goranefbl