Global Scripts
Background
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:
- The script isn't a supported Registry Script.
- You don't care about interacting with the API provided by the third-party script (e.g. you don't need to use
gtag
from Google Analytics). - You are interacting with the API provided by the third-party script, but you don't care about type safety.
Otherwise, it's recommended to use useScript to load scripts in a safer way.
Usage
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' }
]
}
}
})
Accessing a global script
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>
How it Works
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',
}
}
})