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
gtagfrom 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 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 register 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
Nuxt uses the globals configuration to create a virtual Nuxt plugin that loads in the script using the useScript() composable.
As Nuxt uses useScript() 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',
}
}
})
<script setup lang="ts">
// This will not trigger the script to be loaded again because of the nuxt.config global script
const { proxy, onLoaded } = useNuxtApp().$scripts.tracker
onLoaded(() => {
console.log('Script loaded')
})
function trackCustom() {
proxy.track('custom_event')
}
</script>
<template>
<button @click="trackCustom">
Track Custom Event
</button>
</template>