#Prefetch config
8 messages · Page 1 of 1 (latest)
Hi @daring scaffold. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Yes, prefetching can work on dropdown links or any other navigation that might not always appear as <a /> links. You can prefetch programmatically using the prefetch() API from the astro:prefetch module. Here's an example:
<button id="btn">Click me</button>
<script>
import { prefetch } from 'astro:prefetch';
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
prefetch('/about');
});
</script>
In this example, when the button with id btn is clicked, the /about page is prefetched. You can replace the /about with the path of the page you want to prefetch when a dropdown link is clicked.
The prefetch() API includes the same data saver mode and slow connection detection so that it only prefetches when needed. To ignore slow connection detection, you can use the ignoreSlowConnection option:
// Prefetch even on data saver mode or slow connection
prefetch('/about', { ignoreSlowConnection: true });
Remember to only import prefetch() in client-side scripts as it relies on browser APIs.
For more information, you can refer to the Astro Prefetch Guide (https://docs.astro.build/en/guides/prefetch/#prefetch-programmatically).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@daring scaffold kapa.ai is still learning and improving, please let us know how it did by reacting below
in react?
@worldly lynx I have this code
const handleMouseEnter = (href) => {
console.log('prefetching', href);
prefetch(href);
};
but I notice that some link are not prefetching on my network tab? what should be the issue?
Let me check the knowledge base for you. One moment! :books:
There could be several reasons why some links are not being prefetched:
-
External Links: Prefetching only works for links within your site, not for external links. If the
hrefin your function refers to an external link, prefetching will not work. -
Browser Support: Astro’s prefetching uses
<link rel="prefetch">if supported by the browser, and falls back to thefetch()API otherwise. Some browsers like Safari do not support<link rel="prefetch">and will fall back to thefetch()API which requires cache headers to be set. Otherwise, the prefetch will not work. -
Data Saver Mode or Slow Connection: If a visitor is using data saver mode or has a slow connection, prefetch will fallback to the
tapstrategy. Quickly hovering or scrolling over links will not prefetch them. -
Prefetch Configuration: Ensure that prefetching is enabled in your Astro configuration. If it's not enabled, the prefetch function will not work.