Learn Performance - Dynamic import()

Conditional import()

Dynamic import() allows you to conditionally download a JavaScript module. This page checks the user's prefers-reduced-motion preference.

  • If it is set to no-preference (default) then it will download canvas-confetti.js and attach an event listener to the button.
  • If the user's preference is set to reduce, this indicates that the page should minimize movement and animation. Consequently, confetti.js will not be downloaded.

Note how the button is disabled until polyfill.js is downloaded and executed.

View Source Code
const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
  if (!mediaQuery.matches) {
    await import("../canvas-confetti.js?delay=1000");
    document.getElementById("clickMe").addEventListener("click", () => {
      confetti({ particleCount: 100, spread: 70, origin: { y: 0.6 } });
    });
  }