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
string
Script specified url.
immediate?
boolean
Load the script immediately.
true
async?
boolean
Add async attribute to the script tag.
true
type?
string
Script type.
text/javascript
crossOrigin?
anonymous | use-credentials
Define 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-url
Indicates which referrer to send when fetching the script, or resources fetched by the script.
noModule?
boolean
This 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?
boolean
Scripts with the defer attribute will execute in the order in which they appear in the document.
document?
Document
Specify a custom document instance, e.g. working with iframes or in testing environments.
Default document
onLoaded?
(el: HTMLScriptElement) => void
Utility function that is called when script has loaded.
onError?
(el: HTMLScriptElement, event?: ErrorEvent | UIEvent) => void
Utility function that is called on abort or loading error.
attrs?
Record<string, string>
Add custom attribute to the script tag.
autoUnload?
boolean
Whether 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) => Promise
Utility function to load script tag element manually.
unload
() => void
Utility function to unload script tag element from the page.