Skip to content

Loading

js
import { 
loadImage
,
loadLink
,
loadScript
} from '@studiometa/js-toolkit/utils';

Three promises over three tags. Each resolves with the element it created, so a caller can read the loaded image's natural size, or keep the script tag to remove it later.

Usage

js
import { 
loadImage
,
loadLink
,
loadScript
} from '@studiometa/js-toolkit/utils';
async function
load
() {
const
img
= await
loadImage
('/hero.webp');
await
loadScript
('https://example.com/widget.js', {
async
: '',
crossorigin
: 'anonymous' });
await
loadLink
('/print.css', {
rel
: 'stylesheet',
media
: 'print' });
}

loadImage

ts
loadImage(src: string): Promise<HTMLImageElement>

loadScript

ts
loadScript(src: string, attributes?: Record<string, string>): Promise<HTMLScriptElement>
ts
loadLink(href: string, attributes: { rel: string; [key: string]: string }): Promise<HTMLLinkElement>

Where they belong

A third-party widget, a heavy stylesheet or a decorative image is exactly what a deferred mount is for. Reach for these inside a component whose mount is already deferred, rather than as a substitute for deferring it:

html
<div data-component="Widget" data-mount="interaction:page"></div>
js
mounted() {
  return loadScript('https://example.com/widget.js').then(() => this.init());
}

The mount strategy decides when, and these decide what.

What is not here

loadIframe and loadElement are not ported. An iframe is one createElement() and one load listener, and a generic element loader had no caller that a specific one did not serve better.

MIT Licensed