# CrootJS > CrootJS is a set of small, dependency-free vanilla JavaScript ES6+ modules meant to be imported directly from a CDN (jsDelivr, serving files straight from GitHub tags) — no npm install, no bundler, no build step. Each module is an independent file; import only the ones you need. CrootJS is the successor of JSCroot (`jscroot/lib` on jsDelivr, jscroot.github.io). Code written for JSCroot: switch imports to `crootjs/lib@` and see the migration table (removed functions, old `api.js` argument order) at https://croot.js.org/docs/en/migrasi. Current release: see the `v*` tags at https://github.com/crootjs/lib/tags (changes per version: https://github.com/crootjs/lib/blob/main/CHANGELOG.md) — import a specific module as `https://cdn.jsdelivr.net/gh/crootjs/lib@/.js`, e.g. `https://cdn.jsdelivr.net/gh/crootjs/lib@0.0.43/cookie.js`. Always pin an exact version tag; do not use `@latest` in production code. For production, import the `.min.js` variant instead (since 0.0.38 release tags contain their own `.min.js` files whose relative imports point to `.min.js` siblings). Never mix `.js` and `.min.js` on one page: they are different module URLs, so shared modules load twice with separate state. Pin to a tag, not a commit SHA from `main` (`.min.js` files are only in release commits). Modules that import others (e.g. `api` -> `storage`; `auth` -> `cookie`, `api`, `storage`, `url`, `element`, `template`, `useragent`, `qr`; `map*` -> `geo`; `mapmodel` -> `model3d`; full list at https://croot.js.org/docs/#memuat-lebih-cepat-dengan-modulepreload): add `` for each imported module and its dependencies so they download in parallel instead of one round trip per import level. E.g. `https://cdn.jsdelivr.net/gh/crootjs/lib@0.0.43/cookie.min.js`. Use the unminified `.js` only for local reading/debugging. SRI (since 0.0.42 every release has `integrity.json` at `https://cdn.jsdelivr.net/gh/crootjs/lib@/integrity.json`: `{ files: { "": "sha384-..." }, imports: { ".min.js": [...] } }` for every `.js`, `.min.js` and `.css`, and since 0.0.43 `.min.css` (built by CrootJS; before that jsDelivr minified `.min.css` itself, so don't hash 0.0.42's). Stylesheets with `integrity` need `crossorigin="anonymous"`. `integrity` on `modulepreload` alone is enforced only by Chromium; to make Chromium, Firefox and Safari reject a changed module, install an import map with an `integrity` key from `integrity.js`, a classic script loaded first in `` (``, before any modulepreload or module script; the one allowed exception to "JS as type=module", because Firefox ignores an import map added after module loading started). It creates ` ``` On the croot.js.org landing page this moves the first API request about 300 ms earlier at 150 ms latency. The table above is generated from the code with `python3 tools/module-deps.py` in the `lib` repo. The `integrity` attributes in the example are explained in the next section. `python3 tools/module-deps.py ` prints the `modulepreload` lines of every module with their hashes. ### Locking file contents with `integrity` (SRI) Pinning a version keeps the URL the same, not the content: what is behind `@0.0.41` still depends on jsDelivr and GitHub. With an SRI (Subresource Integrity) hash the browser hashes the downloaded file and refuses to run it when the hash doesn't match. Since 0.0.42 every release includes `integrity.json` (`https://cdn.jsdelivr.net/gh/crootjs/lib@/integrity.json`): sha384 hashes of every `.js`, `.min.js`, `.css`, and (since 0.0.43) `.min.css`, plus the modules each module imports. `integrity` on `` alone is not enough: only Chromium rejects a changed file, Firefox and Safari still run the module loaded by `import`. All three enforce an import map with an `integrity` key, and that import map also covers imports inside modules (`api.min.js` imports `storage.min.js`). Install it from `integrity.js`, the first script in `` and a **classic** one (the only exception to the [ES module rule](../conventions#2-javascript-must-be-loaded-as-an-es-module)): ```html ``` ```javascript // integrity.js: import map with the SRI hashes of the CrootJS modules. A classic script loaded // first, because Firefox ignores an import map added after a module or preload started loading. const map = document.createElement("script"); map.type = "importmap"; map.textContent = JSON.stringify({ integrity: { "https://cdn.jsdelivr.net/gh/crootjs/lib@0.0.43/api.min.js": "sha384-FkrcJYDj82Td9axSh3O+A2TIpwCIg67PsrurLGMr5vk4KnL8c+zONZlBbaMEU0Cy", "https://cdn.jsdelivr.net/gh/crootjs/lib@0.0.43/storage.min.js": "sha384-I68UpwZkgCfB4R68KBk7oSjwdRZqI+8zHf73gCvG+J2YFk5fxD3kBQjgt45dGk0Z" } }); document.currentScript.after(map); ``` - List every module the page imports **and** the ones in the "Also loads" column (`openapi.js` also loads `yaml.js` and `markdown.js` when needed). A module missing from the list still loads, just unchecked; `bump-pins.py` reports it. - Put the same hash on `modulepreload`. Without it Chromium discards the preloaded copy and downloads the module again. - Modules need no `crossorigin` (they are always requested with CORS), but CSS does: ``; without it the browser rejects a cross-origin stylesheet that has `integrity`. `.min.css` files are part of releases (and `integrity.json`) since 0.0.43; for 0.0.42 use `.css`, because its `.min.css` was minified by jsDelivr itself and its hash is not guaranteed to stay the same. - No need to write hashes by hand: write `integrity=""` or `"…/api.min.js": ""`, then run `bump-pins.py` (next section) to fill them in. - Browsers that don't know `integrity` in import maps still load the modules, unchecked. If the page already has its own import map, add the `integrity` key there. The Draco decoder that `model3d.js` downloads from gstatic.com is not covered. ### Bumping versions with `bump-pins.py` The version is written in several places (imports, `modulepreload`, `integrity.js`) and the hashes change with every version. Missing one means the same module is downloaded twice, or rejected by the browser. `tools/bump-pins.py` (just Python 3, no packages) replaces them all in a folder: ```sh curl -fsSLO https://raw.githubusercontent.com/crootjs/lib/main/tools/bump-pins.py python3 bump-pins.py latest . # or a specific version: python3 bump-pins.py 0.0.42 . ``` Every `crootjs/lib@x.y.z` in `.html`, `.js`, `.md`, `.txt`, and `.json` files becomes the new version, and every `integrity` next to a CrootJS URL gets that version's hash (from `integrity.json`, or from the downloaded file for versions before 0.0.42). If one hash can't be fetched, no file is written. `latest` reads https://croot.js.org/lib/version.json. To get a pull request for every new version (like Dependabot), copy this workflow into your repo. In Settings → Actions → General, enable "Allow GitHub Actions to create and approve pull requests". Pull requests opened with `github.token` don't trigger other workflows, so your CI won't run on them automatically. ```yaml # .github/workflows/crootjs.yml name: crootjs on: schedule: - cron: "0 2 * * 1" workflow_dispatch: permissions: contents: write pull-requests: write jobs: bump: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - env: GH_TOKEN: ${{ github.token }} run: | VERSION=$(curl -fsS https://croot.js.org/lib/version.json | jq -r .version) branch="crootjs-$VERSION" if git ls-remote --exit-code origin "refs/heads/$branch" > /dev/null; then exit 0; fi curl -fsSL https://raw.githubusercontent.com/crootjs/lib/main/tools/bump-pins.py -o /tmp/bump-pins.py python3 /tmp/bump-pins.py "$VERSION" . if git diff --quiet; then exit 0; fi git config user.name "github-actions[bot]" git config user.email "41898341+github-actions[bot]@users.noreply.github.com" git switch -c "$branch" git commit -am "CrootJS $VERSION" git push origin "$branch" gh pr create --title "CrootJS $VERSION" --body "https://github.com/crootjs/lib/releases/tag/v$VERSION" ``` ## Module Reference Per-module documentation for `crootjs/lib`: - [api.js](api/) — `getJSON`, `postJSON`, `putJSON`, `deleteJSON` (callback or `await`, headers, timeout, cancellation, ETag cache), `uploadFile` with progress, `downloadFile` - [element.js](element/) — `onClick`, `setInner`, `getValue`, `serializeForm`, `fillForm`, and other DOM helpers - [croot.css](css) — small, green CSS framework (~2 KB gzipped): plain HTML looks finished without classes, plus layout (`.container`, `.stack`, `.cluster`, `.grid`), cards, badges, alerts, navigation, dark mode, and theming through CSS variables; optional `icons.css` (49 icons, ~1.9 KB gzipped) - [ui.css, themes.css, tabs.js](ui) — optional app components (shell with sidebar, tabs, menus, accordion, summary numbers, switch, steps, and more), four themes with character (`kampus`, `kertas`, `kontras`, `niaga`), `initTabs`, and copy-ready [page patterns](https://croot.js.org/examples/pola/) - [form.js](form) — form validation with a message under each field, screen-reader friendly (`handleForm`, `validateForm`, `clearFormErrors`) - [router.js](router) — single-page app router: hash/history mode, `:id` params, query, 404 page, async handlers, focus and `aria-current` (`startRouter`) - [table.js](table) — data table: per-column sort, search, pagination, server mode; replaces jQuery DataTables (`createTable`) - [chart.js](chart) — hand-written SVG bar, line, and donut charts: round-number axes, Indonesian number format, dark mode, accessible data table and keyboard tooltips (`createChart`) - [markdown.js](markdown) — Markdown to safe HTML (raw HTML escaped, dangerous URLs rejected), render into an element, load `.md` files (`markdownToHTML`, `renderMarkdown`, `getMarkdown`) - [qr.js](qr) — QR codes as SVG, written from scratch (`renderQR`, `qrSVG`, `qrMatrix`) - [openapi.js](openapi) — API documentation from `openapi.yaml`/`.json`, a Swagger UI replacement, with `api.js` code and a try-it button per operation (`renderOpenAPI`, `loadOpenAPI`, `openAPIExample`); its YAML parser is `yaml.js` (`parseYAML`) - [cookie.js](cookie) — set/get/delete cookies - [storage.js](storage) — set/get/delete data in localStorage & sessionStorage (with an optional expiry) - [debounce.js](debounce) — `debounce`/`throttle` to limit how often a function runs (search-as-you-type, scroll, etc.) - [toast.js](toast) — lightweight notifications with no external dependency (`toast`, `toastSuccess`, `toastError`, `toastWarning`, `toastInfo`) - [pwa.js and serviceworker.js](pwa) — installable apps that still open without internet: a service worker on your own domain, new-version notice, online/offline status, install button (`registerServiceWorker`, `installButton`, `crootjsServiceWorker`) - [geo.js](geo) — read GeoJSON geospatial data from a URL or a local file (`getGeoJSON`, `readGeoJSONFile`, `parseGeoJSON`), plus bounding box, center point, and property list - [map.js](map) — interactive maps with no external library: tile basemaps (OpenStreetMap), GeoJSON drawing, popups, coordinate clicks, right-click, named layers, labels, hover, basemap switching, canvas renderer (`createMap`, `addGeoJSON`, `fitMap`, `onMapClick`, `onMapContextMenu`, `showLayer`, `setTiles`) - [mapmarker.js](mapmarker) — `map.js` add-on: pin markers, icons, or your own element, with labels, popups, and dragging (`addMarker`) - [mapcontrol.js](mapcontrol) — `map.js` add-on: scale bar, "my location", live tracking, basemap picker (list or picture cards), layer checklist, coordinates, right-click menu, and fullscreen (`addScaleBar`, `addLocateButton`, `locateUser`, `addTrackButton`, `trackUser`, `addBasemapControl`, `setBasemap`, `addLayerControl`, `addCoordinateControl`, `addContextMenu`, `addFullscreenButton`) - [maptools.js](maptools) — `map.js` add-on: distance and area measuring tools (keyboard included), georeferenced images with rotation, PNG export (`addMeasureControl`, `addImageOverlay`, `exportMapImage`) - [mapcluster.js](mapcluster) — `map.js` add-on: point clustering for very large point datasets (`addCluster`) - [mapsearch.js](mapsearch) — `map.js` add-on: find places by name/address and the address at a point (Nominatim/OSM or your own provider), plus a search box (`searchPlace`, `reverseGeocode`, `addSearchControl`) - [mapoffline.js](mapoffline) — `map.js` add-on: basemap from a single raster or vector PMTiles file, from a server or from a file on the device with no internet (`openPMTiles`) - [mapcache.js](mapcache) — `map.js` add-on: tiles you have viewed are stored in the browser and keep showing while offline, plus area download for your own tile server (`cachedTiles`) - [mapvector.js](mapvector) — MVT vector tiles drawn in the browser, with a replaceable style (`decodeMVT`, `renderVectorTile`, `DEFAULT_VECTOR_STYLE`) - [mapmodel.js](mapmodel) — `map.js` add-on: a glTF/GLB 3D model at its location on the map, true to scale in meters (`addModel`) - [mapdraw.js](mapdraw) — `map.js` add-on: draw points, lines, and polygons (keyboard included), then reshape them (move, add, delete vertices); the result is GeoJSON (`addDrawControl`, `startDrawing`, `editFeature`) - [mapheat.js](mapheat) — `map.js` add-on: point-density heatmaps and square/hexagon grid maps colored by value, like signal coverage maps (`addHeatmap`, `addGridMap`) - [model3d.js](model3d) — glTF/GLB 3D model viewer without Three.js (WebGL2, WebGL1 fallback): rotate/zoom, click parts, change colors, hide, position/rotate from code (`createViewer`, `loadModel`, `onModelClick`, `setPartColor`, `setPartVisible`, `setPartTransform`, `fitView`) - [model3dtools.js](model3dtools) — `model3d.js` add-on: HTML labels pinned to the model, move/rotate/scale gizmo, glTF animation, exploded view, cross-sections, distance and angle measurement, AR inside the page (WebXR) or Scene Viewer/Quick Look, `.glb` export (`addHotspot`, `enableTransform`, `playAnimation`, `explodeModel`, `addSection`, `measureModel`, `startAR`, `addARButton`, `exportGLB`, `downloadGLB`) - [geomeasure.js](geomeasure) — distance, length, area, point-in-area, nearest point, radius circle, conversion from a local grid (`getDistance`, `getArea`, `isInside`, `createCircle`, `createAffineTransform`, ...) - [georoute.js](georoute) — shortest route along the lines in GeoJSON data, computed in the browser (`findRoute`) - [url.js](url) — protocol, host, path, query string, hash, redirect - [validate.js](validate) — input validation & formatting (username, phone number, Rupiah) - [websocket.js](websocket) — open/close WebSocket connections - [stp.js](stp) — send/verify/resend WhatsApp OTP - [useragent.js](useragent) — mobile device detection - [trace.js](trace) — track click/touch coordinates - [image.js](image) — random colors (hex & color names) - [loading.js](loading) — loading spinner SVG asset - [mongo.js](mongo) — MongoDB `ObjectId` helpers (browser-only, no DB connection) See also: [lib source code](https://github.com/crootjs/lib) and [implementation examples](https://github.com/crootjs/examples). ## Coding Conventions (Mandatory) All code that uses CrootJS — written by humans or by AI coding agents — **must** keep HTML, CSS, and JS in separate files, and JS must be loaded as `type="module"` (except `integrity.js` for [SRI](#locking-file-contents-with-integrity-sri)). No inline ` ``` **One exception**: loading a third-party library from its own CDN (e.g. Lucide icons, SweetAlert2) via a plain ` ``` Never as a plain classic script. This matches how CrootJS itself is distributed (`import { x } from "https://cdn.jsdelivr.net/gh/crootjs/lib@/module.js"`) and keeps the whole page in strict-mode ES module scope — no accidental globals. One exception: `integrity.js`, the file that installs the import map with [SRI hashes](en/#locking-file-contents-with-integrity-sri) for CrootJS modules, is a classic script (``), the first script in ``. An import map must exist before any module starts loading; Firefox ignores one added later, so a module can't install it, and an inline `