Preconnect and preload to speed up asset download

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-04-24

Preconnect

Downloading images from another domain (e.g. s3) incurs a cost DNS resolution as well as a cost for downloading.

If you know the URL, you can resolve it early / in parallel by adding the following header

link: <https://assets.someserver.com>; rel=preconnect

Implementing the hint as a header allows it to be applied across the whole site with a single configuration change, and as the hint is received in the headers the browser doesn't even need to start parsing the HTML to discover it.

Preload

The preload value of the <link> element's rel attribute lets you declare fetch requests in the HTML's <head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance. - Source

Use this one when you know the exact URL of something you'll need a header of this

<link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'" >

Preloading Javascript is done a bit differently

<link rel="preload" href="used-later.js" as="script">
<!--Then either add the script like so  -->
<script>
  var usedLaterScript = document.createElement('script');
  usedLaterScript.src = 'used-later.js';
  document.body.appendChild(usedLaterScript);
</script>


<!--Or use it with a script tag like the following (i.e. this is in addition to the link tag preloading the same)  -->
<script src="main.js" defer></script>

Prefetch vs Preload

Prefetching works similarly to preloading. The difference is that, when prefetching a resource, the browser considers the resource to be low priority. This means that the resource or asset will load a bit later. Because of this, prefetching is usually implemented with resources that are not required initially, but are used at a later point.

<link
  rel="prefetch"
  as="style"
  onload="this.rel = 'stylesheet'"
  href='https://fonts.googleapis.com/css?family=Roboto:100,900|Material+Icons'>

Source