Plain script
Some droplets are no component at all: an analytics tracker, a third-party
widget, a chat bubble, a vanilla UI. A script droplet is a
+droplet.script.ts (or .js) whose default export runs in the browser
with the droplet’s data and its element. No framework is involved and no
renderer is installed: core builds it.
The droplet below is the same counter as on the other pages. The demo server’s load returns the start and the name; the server sends that data and an empty element; the script builds the card in the browser.
import type { DropletScript } from "./$types";
/** An element with a class and, optionally, its text. */function make<K extends keyof HTMLElementTagNameMap>(tag: K, className: string, text = "") { const element = document.createElement(tag); element.className = className; element.textContent = text; return element;}
/** * Runs in the browser only, once per element. The server sent what its load * returned and an empty `el`: everything below is built here, from `data`. */const counter: DropletScript = (data, el) => { let added = 0;
const card = make("section", "demo-card"); card.dataset["hydrated"] = "true"; const head = make("p", "demo-row"); head.append(make("span", "demo-tag", `counter · ${data.framework}`)); const row = make("p", "demo-row"); const count = make("output", "demo-title", String(data.start)); count.setAttribute("aria-live", "polite"); const button = make("button", "demo-button", "Add one"); button.type = "button"; const onClick = () => (count.textContent = String(data.start + ++added)); button.addEventListener("click", onClick); row.append(count, button); card.append(head, row, make("p", "demo-muted", "Built in the browser: the server sent the data and an empty element.")); el.append(card);
// The cleanup, when the element leaves the page; `el` is emptied after it. return () => button.removeEventListener("click", onClick);};
export default counter;import type { LoadEvent } from "./$types";
/** * Runs on the server only. The count starts where the server says, and the * name of the framework comes with it. The same for everyone, so a browser * (or a cache in front) may keep it for five minutes. */export const load = ({ setHeaders }: LoadEvent) => { setHeaders({ "cache-control": "public, max-age=300" }); return { framework: "plain script", start: 3 };};Add it to a project
Section titled “Add it to a project”npx djs add counter --framework scriptIt installs nothing and edits nothing: script droplets are built into
@dropletsjs/droplets, next to whatever renderers vite.config.ts lists. It
writes src/droplets/counter/+droplet.script.ts and the optional files you
pick, then its ./$types. To answer up front:
npx djs add counter --framework script --with server,css --yes-
--targetand--hydrateare refused with an error: a script droplet is always client only, so it renders nothing on the server and runs at once in the browser; -
--withtakesserver,universalandcss(astyle.cssthe script imports);--with erroris refused too, since a script droplet has no error page. An+error.*file in its folder is ignored, with a warning undervite dev:[droplets:framework] counter/+error.script.ts is ignored: a script droplet has no error page
The files
Section titled “The files”| File | What it is |
|---|---|
+droplet.script.ts, +droplet.script.js |
The script: its default export runs in the browser. It has no flags. |
+droplet.server.ts |
Optional: the server load, as for any droplet; its result comes inline in the fragment. |
+droplet.ts |
Optional: the props schema, and a load that runs on the server and in the browser. |
.script.ts and .script.js belong to core, and no renderer can claim
them; the name also keeps +droplet.ts the load file. The default export:
export default function (data: Data, el: HTMLElement): void | (() => void);datais what the loads returned, as for any droplet: the server load’s result, inline in the fragment (no second request), then the+droplet.tsload’s in the browser. In the demo,{ framework: "plain script", start: 3 }.elis the droplet’s content root inside the element, the<div data-droplet-entry>every droplet has: add anything under it. It is adisplay: contentsbox, so append your own element when the script needs something with a size, as the demo appends its<section>.- The returned function, if any, is the cleanup: it runs when the element
leaves the page, and
elis emptied after it. Anasyncfunction works too: the cleanup its promise resolves to is kept. Undervite dev, an edit to the script runs the cleanup, then the new function on the sameel, without a page reload (Hot updates).
./$types of a script droplet exports DropletScript, the default export
typed with the droplet’s own Data; @dropletsjs/droplets exports a
framework-neutral DropletScript<Data> too:
import type { DropletScript } from "./$types";
const track: DropletScript = (data, el) => { /* data: what the load returned */ };export default track;What it supports
Section titled “What it supports”| Server rendering | no: it is always client only (ssr false); the fragment is the element, its data and an empty el |
hydrate |
always true: it runs as soon as the element connects |
| Prerendering | no |
| Imports | any package, whatever the project’s other droplets are written in |
A script droplet has no flags: it is ssr false, hydrated at once and never
prerendered, whatever the file exports. An exported flag never fails the
build: in vite build and vite dev each one warns once per file and is
ignored. hydrate = true is what it already is:
[droplets:framework] counter/+droplet.script.ts exports hydrate = true; a script droplet is always hydrated (locked to true)Any other flag (ssr with any value, prerender with any value, hydrate
with false, "visible" or "interactive"):
[droplets:framework] counter/+droplet.script.ts exports hydrate = false; this is ignored, a script droplet is client onlyOther named exports are the script’s own business and say nothing.
A host’s data-droplet-hydrate="false" is ignored on a script droplet’s element: a
script droplet only runs in the browser, so there is nothing to keep. Under
vite dev the browser console says so:
[droplets] data-droplet-hydrate="false" on the script droplet "counter" is ignored: a script droplet only runs in the browserdata-droplet-hydrate="visible" still defers it until the element nears the
viewport. data-droplet-hydrate="interactive" runs it at once: there is no server
markup to interact with.
Specifics
Section titled “Specifics”-
What the server sends. The server never imports the file, so it may touch
windowordocumentat the top level. It is the client-only fragment: the props ride on the element asdata-droplet-context, and there is no script that runs, so it stays CSP-clean, like every fragment.<djs-demo data-droplet="counter-script" data-droplet-build="…" data-droplet-context="…"><script type="application/text" data-droplet-payload="data">…</script><link rel="stylesheet" href="…/droplets/counter-script/style.css?c=…" data-droplet-style><div style="display: contents" data-droplet-entry></div></djs-demo> -
In the browser it always runs: the element imports its bundle and calls the default export once per element, each with its own
el. A script that throws is logged ([droplets] <id> failed), whatever it added toelgoes, and the other droplets on the page are not affected. A file whose default export is no function fails the same way, with<id>: +droplet.script.ts must export a default function (data, el). -
Styles.
elis inside the element, in the light DOM: the shared stylesheet (src/app.css, scoped to the element) and a CSS file the script imports apply to what it adds. The demo’s card uses apps/demo’s.demo-cardclasses. -
Server files stay out. As for any droplet,
+droplet.server.tsand every other server file stay out of the browser bundle: a script that imports one failsvite build, andvite devrefuses the import, each naming the chain. Unlike a component, it may import any framework’s packages: the cross-framework check leaves it alone. -
Size. The demo’s script is 1.6 kB (gzip) on top of the droplets runtime: no framework comes with it.
Example: an analytics tracker
Section titled “Example: an analytics tracker”A page-view counter that posts each view to the droplets server’s own endpoint. The server load hands it the count so far; the script shows it, counts the view, shows the new count, and aborts a post still in flight when the element goes.
import { viewsOf } from "../../lib/server/page-views.ts";import type { LoadEvent } from "./$types";
export const load = ({ props }: LoadEvent) => ({ page: props.page, views: viewsOf(props.page) });import droplet from "$droplets/drop";import type { DropletScript } from "./$types";
const track: DropletScript = (data, el) => { const line = document.createElement("p"); line.textContent = `${data.page}: ${data.views} views so far`; el.append(line);
const controller = new AbortController(); fetch(droplet.url("/api/page-views"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ page: data.page }), signal: controller.signal, }) .then((response) => response.json()) .then(({ views }) => (line.textContent = `${data.page}: ${views} views`)) .catch(() => {});
return () => controller.abort();};
export default track;droplet.url() points at the droplets server, not at the host page’s
origin. The endpoint (src/api/page-views/+server.ts) reads the body as
plain data: JSON, one object, one own page field checked against a slug
pattern; see Security.
The example
Section titled “The example”The Svelte example has this tracker as
page-views,
next to its Svelte droplets, with its endpoint in src/api/page-views. From a
clone of the repository:
pnpm install && pnpm buildpnpm --filter @dropletsjs/example-svelte dev # http://localhost:5173: the devtools pageThe devtools page lists page-views with the other droplets.