npm.io
3.0.0 • Published 4d ago

@solid-primitives/script-loader

Licence
MIT
Version
3.0.0
Deps
0
Size
9 kB
Vulns
0
Weekly
0
Stars
1.6K

Solid Primitives Script Loader

@solid-primitives/script-loader

size size stage tested with vitest

Creates a primitive to load scripts dynamically, either for external services or jsonp requests

Installation

npm install @solid-primitives/script-loader
# or
yarn add @solid-primitives/script-loader
# or
pnpm add @solid-primitives/script-loader

How to use it

createScriptLoader

Appends a script (by URL or inline source) to document.head and removes it when the owner is disposed.

import { render } from "@solidjs/web";
import { createSignal } from "solid-js";
import { createScriptLoader } from "@solid-primitives/script-loader";

function Demo() {
  const [status, setStatus] = createSignal("loading...");
  createScriptLoader({
    src: "https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js",
    onLoad: () => setStatus("loaded"),
    onError: () => setStatus("failed to load"),
  });
  return (
    <>
      <p>canvas-confetti: {status()}</p>
      <button disabled={status() !== "loaded"} onClick={() => (window as any).confetti()}>
        Confetti!
      </button>
    </>
  );
}

render(() => <Demo />, document.getElementById("app")!);

createScriptLoader expects a props object with a src property. All the other props will be spread to the script element.

The src prop is required and will be used to set the src or textContent attribute. It can be a string or an accessor.

import { createScriptLoader } from "@solid-primitives/script-loader";

// For example, to use recaptcha:
createScriptLoader({
  src: "https://www.google.com/recaptcha/enterprise.js?render=my_token",
  async onLoad() {
    await grecaptcha.enterprise.ready();
    const token = await grecaptcha.enterprise.execute("my_token", { action: "login" });
    // do your stuff...
  },
});

// or pinterest embeds:
createScriptLoader({
  src: '!function(a,b,c){var d,e,f;d="PIN_"+~~((new Date).getTime()/864e5),...',
  onLoad() {
    window?.PinUtils?.build();
  },
});

Definition

function createScriptLoader(props: ScriptProps): HTMLScriptElement | undefined; // script element with be undefined only on the server

type ScriptProps = Omit<ComponentProps<"script">, "src" | "textContent"> & {
  /** URL or source of the script to load. */
  src: string | Accessor<string>;
};

Changelog

See CHANGELOG.md

Keywords