Tag Placement

How tags are position in the DOM and how to configure them.

Introduction

By default, tags are rendered in the document <head> in a specific order for optimal performance and compatibility.

However, this is not always useful, say if you need to render a script at the end of the document or have a specific placement of a tag.

To solve these two issues we have two options:

  • tagPosition: To control where the tag is rendered in the document (e.g. head, bodyClose, bodyOpen, etc)
  • tagPriority: To control the order of tags within the document section

Document Placement

For the script, noscript and style tags you may provide an optional tagPosition property with the possible values:

  • head - Render in the <head> (default)
  • bodyOpen - Render at the start of the <body>
  • bodyClose - Render at the end of the <body>
import { useHead } from 'unhead'

useHead({
  script: [
    {
      src: '/my-lazy-script.js',
      tagPosition: 'bodyClose',
    },
  ],
})
// renders
//   ...
//   <script src="/my-lazy-script.js"></script>
// </body>

Sort Order

All tags are given a weight with the lower the number, the higher the priority.

Capo.js weights are automatically applied to tags to avoid Critical Request Chains. As well as default weights to avoid site stability issues:

  • -20 - <meta charset ...>
  • -10 - <base>
  • 0 - <meta http-equiv="content-security-policy" ...>
  • 10 - <title>
  • 20 - <link rel="preconnect" ...>

All other tags have a default priority of 100: <meta>, <script>, <link>, <style>, etc

Escaping out of these default weights can be accomplished by setting the tagPriority property.

Using tagPriority

The tagPriority property can be set to an explicit weight, a string alias or a string to target a specific tag.

Sorting with Aliases

You can also make use of a string alias that adjusts the priority by a relative amount:

  • critical - -80
  • high - -10
  • low - 20
useHead({
  script: [
    {
      src: '/my-lazy-script.js',
      tagPriority: 'low',
    },
  ],
})

Sort by number

When providing a number, refer to the priorities set for critical tags above.

// some layout we have a js file that is ran
useHead({
  script: [
    {
      src: '/not-important-script.js',
    },
  ],
})

// but in our page we want to run a script before the above
useHead({
  script: [
    {
      src: '/very-important-script.js',
      tagPriority: 0,
    },
  ],
})

// <script src=\"/very-important-script.js\"></script>
// <script src=\"/not-important-script.js\"></script>

Sort with before: and after:

If you'd like to place a tag before or after another tag, you can use the Alias Sorting plugin.

Hydration Caveats

When hydrating the state (e.g., SSR or page switch), Unhead replaces existing tags in their current position to avoid a flash of content.

This may cause tagPriority to be ignored during hydration.

Did this page help you?