Guides

Script Triggers

Last updated by Harlan Wilton in chore: lint.
Try the live Performance Example on StackBlitz to see triggers in action.

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.

How Triggers Work

Pass any reactive value as trigger - the script loads when it becomes truthy:

const shouldLoad = ref(false)

useScript('https://example.com/script.js', {
  trigger: shouldLoad
})

// Later: trigger loading
shouldLoad.value = true

This works with refs, computed refs, getter functions, and promises:

// Ref
trigger: shouldLoad

// Computed
trigger: computed(() => !!route.query.affiliateId)

// Getter function
trigger: () => shouldLoad.value

// Promise
trigger: new Promise(resolve => setTimeout(resolve, 3000))

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 })
})

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']
  })
})

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()