Script Tag
Script tag injecting.
# Anatomy
Using the code below, when the component is mounted, the script will be loaded automatically, and it will be removed upon destroying of the component.
<script>
import { createScriptTag } from '@grail-ui/svelte';
createScriptTag({
url: 'https://player.twitch.tv/js/embed/v1.js',
onLoaded() {
// do something
},
});
</script># Examples
# Manual load/unload
To have manual control over the timing of loading and unloading the script, use immediate: false
and/or autoUnload: false.
const { load, unload } = createScriptTag({
url: 'https://player.twitch.tv/js/embed/v1.js',
onLoaded: () => new Twitch.Player(twitchEl, { width: 500, height: 400, channel: 'monstercat' }),
immediate: false,
autoUnload: false,
});
// manual controls
load();
unload();# API
# ScriptTagConfig
| Property | Description | Default |
|---|---|---|
url |
stringScript specified url. |
— |
immediate? |
booleanLoad the script immediately. |
true |
async? |
booleanAdd async attribute to the script tag. |
true |
type? |
stringScript type. |
text/javascript |
crossOrigin? |
anonymous | use-credentialsDefine how the element handles cross-origin requests. |
— |
referrerPolicy? |
no-referrer | no-referrer-when-downgrade | origin | origin-when-cross-origin | same-origin | strict-origin | strict-origin-when-cross-origin | unsafe-urlIndicates which referrer to send when fetching the script, or resources fetched by the script. |
— |
noModule? |
booleanThis Boolean attribute is set to indicate that the script should not be executed in browsers that support ES2015 modules and can be used to serve fallback scripts to older browsers that do not support modular JavaScript code. |
— |
defer? |
booleanScripts with the defer attribute will execute in the order in which they appear in the document. |
— |
document? |
DocumentSpecify a custom document instance, e.g. working with iframes or in testing environments. |
Default document |
onLoaded? |
(el: HTMLScriptElement) => voidUtility function that is called when script has loaded. |
— |
onError? |
(el: HTMLScriptElement, event?: ErrorEvent | UIEvent) => voidUtility function that is called on abort or loading error. |
— |
attrs? |
Record<string, string>Add custom attribute to the script tag. |
— |
autoUnload? |
booleanWhether unload script tag element from the page when component is destroyed. |
true |
# ScriptTagReturn
| Property | Description |
|---|---|
scriptTag |
Readable<HTMLScriptElement | null>Script tag element. |
load |
(waitForScriptLoad?: boolean) => PromiseUtility function to load script tag element manually. |
unload |
() => voidUtility function to unload script tag element from the page. |