Create a trigger for an element to load a script based on specific element events.
function useScriptTriggerElement(options: ElementScriptTriggerOptions): Promise<void> & { ssrAttrs?: Record<string, string> } | 'onNuxtReady' {}
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
}
A promise that resolves when the script is loaded.
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 event listener will not be attached to the element, and the script will not be loaded.
To ensure this is handled correctly you should bind the ssrAttrs
value to the element you're attaching events to. 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>
<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>
<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>