Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C3 · Урок 4
ЗавданняInline approximation: simulate the dynamic-import pattern. On button click, log 'loading...', then resolve a Promise (use Promise.resolve({ greet: name => `hi, ${name}` })), destructure greet, log greet('Anna').

Динамічний імпорт(): завантажувати код на вимогу

100 XP8 min
Теорія

import() as a function

Static imports run at module-load time. import() as a function call returns a Promise that resolves to the module:

const { format } = await import("./big-formatter.js");
console.log(format(today));

The file isn't fetched until import() runs. That means you can lazy-load chunks of your app — admin pages, optional features, polyfills you only need on old browsers.

The classic example

button.addEventListener("click", async () => {
  const { default: heavyEditor } = await import("./editor.js");
  heavyEditor.mount("#workspace");
});

The editor module is fetched the first time the user clicks the button. Until then, none of its bytes are downloaded.

Why bundlers care

import() is a hint to bundlers ("create a separate chunk"). Webpack, Vite, esbuild all turn each dynamic import into its own .js chunk, lazy-loaded over fetch. That's how you ship a 50KB initial bundle that grows to 500KB only when users explore deeper.

Catch errors

try {
  const mod = await import("./optional.js");
} catch (e) {
  // module failed to load — fall back gracefully
}

Static imports throw at module-load (whole page breaks). Dynamic imports can fail at runtime — wrap them in try/catch if the module is genuinely optional.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.