@jobscale/loading
v0.0.4
Published
html loading
Readme
@jobscale/loading
A browser loading overlay module.
Calling loading(pending, options) appends a full-screen translucent overlay
with an animated SVG spinner in the center to document.body.
It waits for the given value (pending) — either a single Promise or an
array of Promises — to settle, guarantees a minimum display duration
(options.milliseconds, default 500ms), then removes the overlay
automatically. By default, it returns the resolved value and throws the first
exception when a pending value rejects. Set options.settled to true to
receive the PromiseSettledResult values instead.
Features
- No dependencies (pure ESM)
- Inline SVG bundled as a data URL — no network request required
- Prevents duplicate overlays (subsequent calls while visible are ignored)
- Covers the full viewport (
position: fixed/z-index: 101)
Installation
Via CDN (when loading as type="module"):
<script type="module">
import { loading } from 'https://esm.sh/@jobscale/loading';
await loading(fetch('/api/data'));
</script>From a classic <script> (no type="module"), use dynamic import().
Top-level await is not available in classic scripts, so wrap the call in
an async function or IIFE:
<script>
(async () => {
const { loading } = await import('https://esm.sh/@jobscale/loading');
await loading(fetch('/api/data'));
})();
</script>You can also cache the module promise and reuse it across handlers:
<script>
const loadingModule = import('https://esm.sh/@jobscale/loading');
document.getElementById('btn').addEventListener('click', async () => {
const { loading } = await loadingModule;
await loading(fetch('/api/data'));
});
</script>Via npm:
npm install @jobscale/loadingimport { loading } from '@jobscale/loading';Usage
Pass a Promise and the overlay will be displayed until it settles.
By default, loading() returns the resolved value and throws the first
exception when the Promise rejects.
import { loading } from 'https://esm.sh/@jobscale/loading';
function fetchData() {
loading(fetch('/api/data'))
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}You can also pass an array of Promises. The overlay stays visible until all
of them settle, and an array of resolved values is returned in the same order.
If any Promise rejects, the first exception is thrown.
- CASE 1
const customFetch = () => fetch('/api/custom');
const customData = { data: 'i am me' };
const fetchAll = () => loading([
fetch('/api/data'),
fetch('/api/config'),
fetch('/api/user'),
customFetch,
customData,
]);
fetchAll()
.then(([dataResponse, config, user]) => dataResponse.json())
.then(data => console.log(data))
.catch(error => console.error(error));- CASE 2
const customFetch = () => fetch('/api/custom');
const customData = { data: 'i am me' };
const fetchAll = () => Promise.all([
fetch('/api/data'),
fetch('/api/config'),
fetch('/api/user'),
customFetch(),
Promise.resolve(customData),
]);
loading(fetchAll)
.then(([dataResponse, config, user]) => dataResponse.json())
.then(data => console.log(data))
.catch(error => console.error(error));- CASE 3
const customFetch = () => fetch('/api/custom');
const customData = { data: 'i am me' };
const fetchAll = () => [
fetch('/api/data'),
fetch('/api/config'),
fetch('/api/user'),
customFetch,
customData,
];
loading(fetchAll())
.then(([dataResponse, config, user]) => dataResponse.json())
.then(data => console.log(data))
.catch(error => console.error(error));Set settled: true when you need the status and value or reason of each
operation instead of throwing on rejection.
const result = await loading(fetch('/api/data'), { settled: true });
if (result.status === 'fulfilled') {
console.log(await result.value.json());
} else {
console.error(result.reason);
}Pass an options object as the second argument to customize the minimum display time or the appearance.
// Keep the overlay visible for at least 1200ms
const res = await loading(fetch('/api/data'), { milliseconds: 1200 });
// Disable the minimum display time (close as soon as `pending` resolves)
const res2 = await loading(fetch('/api/data'), { milliseconds: 0 });
// Adjust stacking order and spinner size
const res3 = await loading(fetch('/api/data'), {
zIndex: '9999',
backgroundSize: '15% auto',
backgroundColor: 'rgba(22, 22, 33, 0.7)',
});API
loading<T>(pending: Promise<T> | Promise<unknown>[], options?: LoadingOptions): Promise<T | T[] | PromiseSettledResult<T> | PromiseSettledResult<T>[]>
pending— aPromiseto wait for, or an array ofPromises.options— optional object to customize the overlay.- Returns — by default, the resolved value after the overlay is removed. When
pendingis an array, resolved values are returned in the same order. - Rejections — the first exception is thrown by default.
- When
settledistrue, returns aPromiseSettledResult({ status: 'fulfilled', value }or{ status: 'rejected', reason }). Whenpendingis an array, an array ofPromiseSettledResults is returned in the same order. - The overlay stays visible for whichever is longer: the settling of every
pendingpromise oroptions.milliseconds. pendingmay contain Promises, functions returning Promises, or values.- If an overlay is already visible, the call is a no-op and simply returns
the given
pendingvalue as-is.
LoadingOptions
| Key | Type | Default | Description |
| --- | --- | --- | --- |
| milliseconds | number | 500 | Minimum display time in milliseconds. |
| zIndex | string | '101' | z-index of the overlay element. |
| backgroundSize | string | '25% auto' | background-size of the spinner image. |
| backgroundColor | string | 'rgba(0, 0, 0, 0.7)' | background-color of the overlay. |
| settled | boolean | false | Return settled results instead of resolved values and thrown exceptions. |
loadingImage
The data URL string of the SVG spinner used internally. Import it if you want to reuse the spinner image in your own elements.
import { loadingImage } from 'https://esm.sh/@jobscale/loading';
const el = document.createElement('img');
el.src = loadingImage;Default export
An object containing loading and loadingImage.
import app from 'https://esm.sh/@jobscale/loading';
await app.loading(pending);License
MIT
