Guides

Triggering Script Loading

Nuxt Scripts provides several ways to trigger the loading of scripts.

Nuxt Scripts provides several ways to trigger the loading of scripts.

import { useTimeout } from '@vueuse/core'

const { ready } = useTimeout(3000)
useScript({
  src: 'https://example.com/script.js',
}, {
  // load however you like!
  trigger: ready, // refs supported
})

Default Behavior

By default, scripts are loaded when Nuxt is fully hydrated. You can change this default by modifying the defaultScriptOptions.

Element Event Triggers

The useScriptTriggerElement composable allows you to hook into element events as a way to load script. This is useful for loading scripts when a user interacts with a specific element.

const somethingEl = ref<HTMLElement>()
const { trigger } = useScript({
  src: 'https://example.com/script.js',
}, {
  trigger: useScriptTriggerElement({
    trigger: 'hover',
    somethingEl,
  })
})

It has support for the following triggers:

  • visible - Triggered when the element becomes visible in the viewport.
  • mouseover - Triggered when the element is hovered over.

Manual Trigger

The manual trigger allows you to manually trigger the loading of a script. This gives you complete control over when the script is loaded.

const { load } = useScript('https://example.com/script.js', {
  trigger: 'manual'
})
// ...
load()

Promise

You can use a promise to trigger the loading of a script. This is useful for any other custom trigger you might want to use.

const myScript = useScript('/script.js', {
  // load after 3 seconds
  trigger: new Promise(resolve => setTimeout(resolve, 3000))
})

Ref

You can use a ref to trigger the loading of a script. This is useful for any other custom trigger you might want to use.

const myRef = ref(false)
const myScript = useScript('/script.js', {
  trigger: myRef
})
// ...
myRef.value = true