While the app.head
method in Nuxt Config allows for loading global scripts, it can be cumbersome and requires manual optimization.
export default defineNuxtConfig({
head: {
script: [ { src: 'https://analytics.com/tracker.js', async: true } ]
}
})
A simpler method is now available: directly input the script URL into scripts.globals
. You can also include optional settings to tailor the script loading process with specific optimizations in mind.
You may consider using global scripts when:
gtag
from Google Analytics).Otherwise, it's recommended to use useScript to load scripts in a safer way.
The globals
key supports strings, objects and arrays.
Example: Load a script using just the src
export default defineNuxtConfig({
scripts: {
globals: {
myScript: 'https://analytics.com/tracker.js',
}
}
})
Example: Load a script while providing extra script attributes
export default defineNuxtConfig({
scripts: {
globals: {
myScript: {
src: 'https://example.com/script.js',
integrity: 'sha256-abc123',
}
}
}
})
You can optionally provide the script as an array which allows you to provide Script Options.
export default defineNuxtConfig({
scripts: {
globals: {
myScript: [
{ src: 'https://example.com/script.js' },
// load the script as part of the hydration process instead of on idle
{ trigger: 'client' }
]
}
}
})
All Nuxt Scripts are registered on the $scripts
Nuxt App property.
For scripts registered through nuxt.config, type autocompletion is available.
<script setup lang="ts">
const { $scripts } = useNuxtApp()
$scripts.myScript // { $script, instance }
</script>
The globals
configuration will be used to create a virtual Nuxt plugin that loads in the script using the useScript
composable.
As useScript
is being used under the hood, it's important to understand the defaults and behavior of the useScript composable..
export default defineNuxtConfig({
scripts: {
globals: {
tracker: 'https://analytics.com/tracker.js',
}
}
})