Api
useScriptTriggerElement()
Last updated by Harlan Wilton in chore: lint.
Create a trigger for an element to load a script based on specific element events.
Signature
function useScriptTriggerElement(options: ElementScriptTriggerOptions): Promise<void> & { ssrAttrs?: Record<string, string> } | 'onNuxtReady' {}
Arguments
export interface ElementScriptTriggerOptions {
/**
* The event to trigger the script load.
*
* For example we can bind events that we'd normally use addEventListener for: `mousedown`, `mouseenter`, `scroll`, etc.
*/
trigger?: 'immediate' | 'visible' | string | string[] | false | undefined
/**
* The element to watch for the trigger event.
* @default document.body
*/
el?: HTMLElement | Ref<HTMLElement | undefined> | null
}
Returns
A promise that resolves once the script loads.
Handling Pre-Hydration Events
When registering a trigger that depends on user input, such as mousedown, it's possible that the user will interact with the element before the hydration process is complete.
In this case, the browser won't attach the event listener to the element and won't load the script.
To ensure correct handling, you should bind the ssrAttrs value to the element where you're attaching events. Note that you should verify
that a promise is returned from the function before using the ssrAttrs value.
<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
- Load a script when an element is 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>
- Load a script when an element is hovered over.
<script setup lang="ts">
const el = ref<HTMLElement>()
useScript('/script.js', {
trigger: useScriptTriggerElement({
trigger: 'hover',
el,
})
})
</script>
<template>
<div ref="el">
<h1>hover me to load the script</h1>
</div>
</template>