Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.2 — Dynamic import() and Code Splitting
JavaScript · Example 1 of 3

Load a module only when the button is pressed

The module's first line ran only after the click. In a real app the URL would be "./chart.js" and the bundler would put it in its own chunk. Press the button again: the module message does not repeat.

import(specifier) loads a module while the program is running and returns a promise of its namespace object, so code can be fetched only when it is needed; bundlers use it to split an app into smaller files called chunks.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write an async function loadAndRun(url) that imports a module, calls its default export with no arguments, and returns the result; if anything fails it returns the string failed.

02

Turn this into lazy loading: import { format } from "./big-date-lib.js"; button.onclick = () => (out.textContent = format(new Date()));.

Explain it without notes

01

How does import() differ from a static import declaration?

02

What does the promise from import() resolve to, and how do you reach the default export?

03

What is code splitting, and how does a bundler decide where to split?

04

What are the costs of lazy loading, and how do you reduce them?

Load a module only when the button is pressed

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Page ready. The chart module is not loaded yet.
chart module: downloaded and run
Drew 3 bars