CodePark/ questions / Loading scripts & resources
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Loading scripts & resources

Explain preload, prefetch, preconnect and dns-prefetch. When would you use each?

All four are resource hints. They differ in what they fetch and how urgently.

rel="preload" fetches a resource the current page needs, at high priority, before the browser would find it on its own. Use it for critical files the browser discovers late. Examples are a web font referenced in CSS, or the LCP image (the largest image on screen) set as a CSS background. It needs an as attribute. Preloads that are never used waste bandwidth.

rel="prefetch" fetches a resource that a future navigation will likely need. It runs at low priority and keeps the file in the HTTP cache. For example, fetch the bundle for the next step of a checkout.

rel="preconnect" opens the connection to another origin early, without fetching anything. That means the DNS lookup, the TCP connection and the TLS (encryption) handshake. Use it for a few critical third-party origins, like a font or image CDN.

rel="dns-prefetch" only does the DNS lookup (finding the server's IP address). It is cheaper, and it is a fallback for less important origins.

Don't overuse hints. Too many of them compete with your critical resources for bandwidth.

  • preload fetches a file for the current page at high priority, and it needs an as attribute.
  • prefetch fetches a file for the next navigation at low priority.
  • preconnect sets up the DNS lookup, TCP connection and TLS handshake to an origin early.
  • dns-prefetch does only the DNS lookup, so it is cheaper.
  • Too many hints compete with your critical resources.