How to order/sort tags in the HTML head with Nuxt 3
Yesterday I had a usecase where i needed a script-tag rendered in the HTML head before every other one. Because the application is build with Nuxt 3, I naturally went straight to the docs, but didn't immediatly find how to do this. So I decided to dive a little deeper into this topic.
Soon I discovered (in the docs) that Nuxt 3 uses @unjs/unhead under the hood. It has a nice documentation about sorting the tags here. Unhead uses the concept of priorities to sort the different tags. I won't go into too much details here because the documentation is quite clear on it, but here's a quick TLDR:
- tags are sorted in ascending priority number, so the lower the number, the sooner it will appear in the document
- all tags have a default priority of 10
useHead({
script: [
{
src: '/very-important-script.js',
tagPriority: 0
}
]
})
Defining tag priority
You can define the priority in two ways: using aliases or directly by assigning numbers.
The predefined aliases are the following.
- 'critical' = 2
- 'high' = 9
- 'low' = 11
As you can see they map to a specific priority number.
useHead({
script: [
{
src: '/my-critical-script.js',
tagPriority: 'critical'
}
]
})
You can always set the priority directly by using numbers, too. Just remember: the lower the number, the higher the priority.
Using before: and after: with tag keys
There is also the possibility to sort the tags by explicitely defining the order. For this to work you need to set a key
on every tag that you want to sort in this way.
useHead({
script: [
{
key: 'i-am-critical',
src: '/my-critical-script.js'
}
]
})
Now you want another script come before this script. You can use after:script:i-am-critical
for that.
useHead({
script: [
{
key: 'i-am-critical',
src: '/my-critical-script.js'
},
{
tagPriority: 'after:script:i-am-critical',
src: '/my-other-critical-script.js'
}
]
})
Using unhead hooks
There is also a third way, how you could achieve tag sorting. Unhead exposes some hooks which you can use to sort. At the time of writing this, those hooks are not exposed by Nuxt, so you can not use them at the moment unfortunately. But I created an issue on GitHub for that 💪
That's it for now, I hope this helps someone searching for the same topic 😊