Solid utility hook to dynamically load an external script.
npm install solid-js solid-create-script
pnpm add solid-js solid-create-script
yarn add solid-js solid-create-script
bun add solid-js solid-create-script
const script = createScript("https://some-library.js");
const script = createScript("https://some-library.js", { async: true, ...scriptAttributes });
const script = createScript("https://some-library.js", { defer: true, ...scriptAttributes });
Under the hood createScript
makes use of the createResource
Solid API when loading the desired script at the specified src
. As such, the result of createScript
is a Resource<Event>
object that allows you to inspect when the script has finished loading or returned an error via script.loading
and script.error
respectively.
When using createScript
, here are some points to be aware of:
- The created
<script>
tag will be appeneded to<head>
. - The created
<script>
tag will not be removed from the DOM when a component that uses this hook unmounts. (i.e. we do not make use ofonCleanup
to remove the<script>
from<head>
). - The hook will ensure no duplicate
<script>
tags referencing the samesrc
will be created. Moreover, when multiple components reference the samesrc
, they will all point to the same shared resource ensuring consistency within the reactive graph.
import { Switch, Match } from "solid-js";
import { createScript } from "solid-create-script";
function App() {
const script = createScript("https://some-library.js");
return (
<Switch fallback={<ScriptProvider>...</ScriptProvider>}>
<Match when={script.loading}>Loading Script...</Match>
<Match when={script.error}>Failed to load script: {script.error.message}</Match>
</Switch>
);
}
Feel free to post any issues or suggestions to help improve this utility hook.