Quick Answer: The Alias Sorting plugin lets you control head tag order using readable before: and after: prefixes instead of arbitrary numbers. Use tagPriority: 'before:script:analytics' to place a script before another.
The Alias Sorting plugin lets you control tag order using descriptive before: and after: prefixes instead of numerical priorities.
Numerical priorities become hard to maintain as your application grows:
Aliases make tag ordering more intuitive and maintainable with declarative relationships between tags.
Add the plugin to your Unhead configuration:
import { createHead } from 'unhead'
import { AliasSortingPlugin } from 'unhead/plugins'
const head = createHead({
plugins: [
AliasSortingPlugin()
]
})
Use before: or after: with the tag type and key:
useHead(unheadInstance, {
// First script
script: [{
key: 'analytics',
src: '/analytics.js'
}],
})
useHead(unheadInstance, {
// This will render before analytics.js
script: [{
src: '/critical.js',
tagPriority: 'before:script:analytics'
}]
})
<script src="/critical.js"></script>
<script src="/analytics.js"></script>
The format is: {before|after}:{tagName}:{key}
For example:
before:script:analytics - Place before the analytics scriptafter:meta:description - Place after the description meta tagbefore:link:styles - Place before the styles link tagYou can order multiple tags relative to each other:
useHead(unheadInstance, {
script: [
{
key: 'third',
src: '/c.js',
tagPriority: 'after:script:second'
},
{
key: 'second',
src: '/b.js',
tagPriority: 'after:script:first'
},
{
key: 'first',
src: '/a.js'
}
]
})
<script src="/a.js"></script>
<script src="/b.js"></script>
<script src="/c.js"></script>
Yes. Alias sorting works alongside numeric priorities. The plugin will preserve the numeric priority of the referenced tag:
useHead(unheadInstance, {
script: [
{
key: 'high-priority',
src: '/important.js',
tagPriority: 0
},
{
src: '/also-important.js',
tagPriority: 'before:script:high-priority'
// Will inherit priority 0 and render first
}
]
})
Ensure critical CSS is loaded before other stylesheets:
useHead(unheadInstance, {
link: [
{
key: 'main-css',
rel: 'stylesheet',
href: '/css/main.css'
},
{
key: 'critical-css',
rel: 'stylesheet',
href: '/css/critical.css',
tagPriority: 'before:link:main-css'
}
]
})
Control the execution sequence of dependent scripts:
useHead(unheadInstance, {
script: [
{
key: 'jquery',
src: '/js/jquery.js'
},
{
key: 'plugin',
src: '/js/jquery-plugin.js',
tagPriority: 'after:script:jquery' // Ensure jQuery loads first
},
{
key: 'app',
src: '/js/app.js',
tagPriority: 'after:script:plugin' // Load app.js last
}
]
})