useScriptTag
A composable to load and unload script tags, manual or automatically.
Basic usage
Header scripts on this page:
Urls |
---|
Import
import useScriptTag from '@leaflink/stash/useScriptTag';
Usage
By default, useScriptTag
will load the script upon the onMounted
event, and unload on the onUnmounted
.
useScriptTag('url');
WARNING
The useScriptTag
composable might unload a script that has already been loaded.
For instance, let's say that you're trying to use useScriptTag
for the same URL in both a ParentComponent
and a ChildComponent
:
<ParentComponent> <!-- uses useScriptTag('#url1') -->
<ChildComponent /> <!-- also uses useScriptTag('#url1') -->
</ParentComponent>
Although only a single script tag will be loaded upon mounting, when ChildComponent
gets unmounted, it will unload the script that might be necessary for the ParentComponent
.
Manually
To manually load and unload a specific script tag, set the manual
option to true
const { load, unload } = useScriptTag('url', { manual: true });
// load and unload at will
load();
unload();
isLoaded
The useScriptTag
composable exposes a isLoaded
boolean flag to indicate whether the script has been loaded or not.
<script setup>
const { isLoaded } = useScriptTag('url');
</script>
<template>
<Button :disabled="!isLoaded">Click me</Button>
</template>
Error
The useScriptTag
composable exposes an error
ref, that will contain any error captured from the script tag, or null
if there's none.
const { error } = useScriptTag('url');
watch(error, console.error);
ScriptTag
The useScriptTag
composable exposes a scriptTag
ref, that will contain the actual HTMLScriptElement if the script is added to the document successfully.
const { scriptTag } = useScriptTag('url');