Preload Web Assets Using HTML Link Tags

By

Using <link> tag you can load assets such as images, fonts, scripts and style right after opening a web page document. This provides a better experience for the visitors and they will not see the half loaded page while loading it.

The common rule for the preload as follows. You should provide the url to the asset and it's resource type.

<link rel="preload" href="path/to/asset" as="resource_type">

To load an image file, you can specify it's url and set image to the type attribute. It is recommended to provide the full url including origin (with domain) instead of a relative path for better SEO.

<link rel="preload" href="https://website.com/path/to/image.png" as="image">

You can also provide the mime type the type attribute to make efficient loading decisions before actually fetching the file. In this MDN page you will find all common mime types available.

<link rel="preload" href="https://website.com/logo.svg" as="image" type="image/svg+xml">

While loading font files, you should set the crossorigin attribute to anonymous so the font your have defined in CSS @font-face rules won't load the same font again.

<link rel="preload" href="./assets/font.woff2" as="font" type="font/woff2" crossorigin="anonymous">

You can also preload script and style files the same way.

<!-- Preload style -->
<link rel="preload" href="./assets/styles.css" as="style">

<!-- Preload script -->
<link rel="preload" href="./assets/script.js" as="script">

In client-side applications, all preloaded assets might not be used right away after loading them. Some assets will be used in different screens, initially hidden components. Due this situation, browser may give your a warning in console about unused assets. A script like this can avoid that warning by creating hidden element to use the preloaded assets.

// get all preload image definitions
const preloads = document.querySelectorAll("link[rel=preload][as=image]")

// for each preload element
for (let i = 0; i < preloads.length; i++) {
  // get image url
  const url = preloads[i].getAttribute("href")

  // create a div element
  const div = document.createElement("div")

  // set image as background
  div.style.backgroundImage = `url(${url})`

  // hide div element
  div.style.position = "fixed"
  div.style.left = "-100px"
  div.style.top = "-100px"

  // append element into body
  document.body.appendChild(div)
}