docs/docs/en/runjs/context/require-async.md
Loads UMD/AMD or global scripts by URL asynchronously; can also load CSS. Use for ECharts, Chart.js, FullCalendar (UMD), jQuery plugins, etc. in RunJS; pass a .css URL to load and inject styles. If a library provides ESM, prefer ctx.importAsync().
Use whenever RunJS needs to load UMD/AMD/global scripts or CSS: JSBlock, JSField, JSItem, JSColumn, event flow, JSAction, etc. Typical: ECharts, Chart.js, FullCalendar (UMD), dayjs (UMD), jQuery plugins.
requireAsync<T = any>(url: string): Promise<T>;
| Parameter | Type | Description |
|---|---|---|
url | string | Script or CSS URL. Supports shorthand <package>@<version>/<path> (ESM CDN adds ?raw for raw UMD) or full URL. .css URLs load and inject styles. |
window (e.g. window.echarts); return value may be undefined—use the library’s docs for how to access..css URLs, returns the result of loadCSS.echarts@5/dist/echarts.min.js; with default ESM CDN (esm.sh) becomes https://esm.sh/echarts@5/dist/echarts.min.js?raw; ?raw fetches the raw UMD file.https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js..css are loaded and injected.window; return may be the lib or undefined.ctx.importAsync() for better module semantics and tree-shaking.const echarts = await ctx.requireAsync('echarts@5/dist/echarts.min.js');
const dayjs = await ctx.requireAsync('https://cdn.jsdelivr.net/npm/dayjs@1/dayjs.min.js');
await ctx.requireAsync('https://cdn.example.com/theme.css');
const container = document.createElement('div');
container.style.height = '400px';
container.style.width = '100%';
ctx.render(container);
const echarts = await ctx.requireAsync('echarts@5/dist/echarts.min.js');
if (!echarts) throw new Error('ECharts library not loaded');
const chart = echarts.init(container);
chart.setOption({
title: { text: ctx.t('Sales overview') },
series: [{ type: 'pie', data: [{ value: 1, name: ctx.t('A') }] }],
});
chart.resize();
async function renderChart() {
const loaded = await ctx.requireAsync('[email protected]/dist/chart.umd.min.js');
const Chart = loaded?.Chart || loaded?.default?.Chart || loaded?.default;
if (!Chart) throw new Error('Chart.js not loaded');
const container = document.createElement('canvas');
ctx.render(container);
new Chart(container, {
type: 'bar',
data: {
labels: ['A', 'B', 'C'],
datasets: [{ label: ctx.t('Count'), data: [12, 19, 3] }],
},
});
}
await renderChart();
const dayjs = await ctx.requireAsync('dayjs@1/dayjs.min.js');
console.log(dayjs?.default || dayjs);
undefined; if undefined, use the lib’s docs (often window).ctx.importAsync().