useScriptTriggerElement()
Load a script when an element becomes visible or receives one of the configured events.
Signature
function useScriptTriggerElement(options: ElementScriptTriggerOptions): (Promise<boolean> & { ssrAttrs?: Record<string, string> }) | 'onNuxtReady'
Arguments
export interface ElementScriptTriggerOptions {
/**
* The event to trigger the script load.
*
* Accepts event names used with addEventListener, such as `mousedown`, `mouseenter`, and `scroll`.
* `visible` and `visibility` use an IntersectionObserver instead.
*/
trigger?: 'immediate' | 'visible' | string | string[] | false | undefined
/**
* The element to watch for the trigger event.
* Event triggers default to document.body. Visibility triggers require an element.
*/
el?: MaybeComputedElementRef<MaybeElement>
}
Returns
A promise that resolves when the configured element event or visibility condition occurs. useScript() then starts loading the script. An omitted, false, 'immediate', or 'onNuxtReady' trigger returns the 'onNuxtReady' sentinel instead.
If the owning Vue scope is disposed before the event occurs, the promise resolves to false; useScript() leaves the script unloaded.
Visibility triggers use an IntersectionObserver with a threshold of 0 and rootMargin: '30px 0px 0px 0px'. The promise resolves when the element intersects that adjusted root, which includes an extra 30 pixels beyond its top edge.
Handling Pre-Hydration Events
A user can interact with an element before hydration attaches its listener. Bind ssrAttrs to that element so a pre-hydration event, such as mousedown, still starts the script. Check that the trigger returned a promise before reading ssrAttrs.
<script setup lang="ts">
import { ref, useScriptTriggerElement } from '#imports'
const el = ref<HTMLElement>()
const trigger = useScriptTriggerElement({
trigger: 'mousedown',
el,
})
const elAttrs = computed(() => {
return {
...(trigger instanceof Promise ? trigger.ssrAttrs : {}),
}
})
</script>
<template>
<div ref="el" v-bind="elAttrs">
Click me to load the script
</div>
</template>
Examples
When an Element Becomes Visible
<script setup lang="ts">
const el = ref<HTMLElement>()
useScript('/script.js', {
trigger: useScriptTriggerElement({
trigger: 'visible',
el,
})
})
</script>
<template>
<div style="height: 100vh;">
<h1>Scroll down to load the script</h1>
</div>
<div ref="el">
<h1>Script loaded!</h1>
</div>
</template>
On Hover
<script setup lang="ts">
const el = ref<HTMLElement>()
useScript('/script.js', {
trigger: useScriptTriggerElement({
trigger: 'mouseenter',
el,
})
})
</script>
<template>
<div ref="el">
<h1>Hover me to load the script</h1>
</div>
</template>