Script Triggers
Nuxt Scripts provides a flexible trigger system to control when scripts load, helping you optimize performance by loading scripts at the right moment for your users.
Default: onNuxtReady
By default, scripts use the onNuxtReady trigger, providing "idle loading" behavior where scripts load only after the page is fully interactive. This minimizes impact on Core Web Vitals and user experience.
The onNuxtReady trigger ensures scripts load:
- After Nuxt hydration is complete
- When the browser is idle and the main thread is available
- Without blocking critical page rendering or user interactions
// Default behavior - explicit for clarity
useScript('https://widget.intercom.io/widget/abc123', {
trigger: 'onNuxtReady'
})
// Registry scripts also use onNuxtReady by default
useScriptGoogleAnalytics({
id: 'GA_MEASUREMENT_ID'
// trigger: 'onNuxtReady' is implied
})
You can change this default by modifying the defaultScriptOptions.
Specialized Triggers
Idle Timeout
Use useScriptTriggerIdleTimeout to delay script loading for a specified time after Nuxt is ready:
useScript('https://example.com/analytics.js', {
trigger: useScriptTriggerIdleTimeout({ timeout: 5000 })
})
export default defineNuxtConfig({
scripts: {
registry: {
googleAnalytics: [{
id: 'GA_MEASUREMENT_ID'
}, {
trigger: { idleTimeout: 3000 }
}]
}
}
})
User Interaction
Use useScriptTriggerInteraction to load scripts when users interact with your site:
useScript('https://example.com/chat-widget.js', {
trigger: useScriptTriggerInteraction({
events: ['scroll', 'click', 'keydown']
})
})
export default defineNuxtConfig({
scripts: {
globals: {
chatWidget: ['https://widget.example.com/chat.js', {
trigger: { interaction: ['scroll', 'click', 'touchstart'] }
}]
}
}
})
Element Events
Use useScriptTriggerElement to trigger scripts based on specific element interactions:
const buttonEl = ref<HTMLElement>()
useScript('https://example.com/feature.js', {
trigger: useScriptTriggerElement({
trigger: 'visible', // or 'hover', 'click', etc.
el: buttonEl,
})
})
Basic Triggers
Manual Control
Use manual trigger for complete control over script loading:
const { load } = useScript('https://example.com/script.js', {
trigger: 'manual'
})
// Load when you decide
await load()
Custom Logic
Use reactive values or promises for custom loading logic:
const shouldLoad = ref(false)
useScript('https://example.com/script.js', {
trigger: shouldLoad
})
// Trigger loading
shouldLoad.value = true
const route = useRoute()
useScript('https://example.com/script.js', {
trigger: computed(() => !!route.query.affiliateId)
})
useScript('https://example.com/script.js', {
trigger: new Promise(resolve => setTimeout(resolve, 3000))
})