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 })
const route = useRoute() useScript({ src: 'https://example.com/script.js', }, { // only if route has a specific query trigger: computed(() => !!route.query.affiliateId), })
import { useTimeout } from '@vueuse/core' const { ready } = useTimeout(3000) useScriptMetaPixel({ id: '1234567890', scriptOptions: { trigger: ready } })
export default defineNuxtConfig({ scripts: { globals: { myScript: ['https://example.com/script.js', { // load however you like! trigger: 'onNuxtReady' }] } } })
By default, scripts are loaded when Nuxt is fully hydrated. You can change this default by modifying the defaultScriptOptions.
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 script = useScript({ src: 'https://example.com/script.js', }, { trigger: useScriptTriggerElement({ trigger: 'hover', el: 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.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()
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)) })
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