Dynamic, Conditional Imports

No Comments

With ES Modules, you can natively import other JavaScript. Like confetti, duh:

import confetti from 'https://cdn.skypack.dev/canvas-confetti';
confetti();

That import statement is just gonna run. There is a pattern to do it conditionally though. It’s like this:

(async () => {
  if (condition) {
    // await import("stuff.js");

    // Like confetti! Which you have to import this special way because the web
    const { default: confetti } = await import(
      "https://cdn.skypack.dev/canvas-confetti@latest"
    );
    confetti();
  }
})();

Why? Any sort of condition, I suppose. You could check the URL and only load certain things on certain pages. You could only be loading certain web components in certain conditions. I dunno. I’m sure you can think of a million things.

Responsible, conditional loading is another idea. Here’s only loading a module if saveData isn’t on:

CodePen Embed Fallback

The post Dynamic, Conditional Imports appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

    About us and this blog

    We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

    Request a free quote

    We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

    Subscribe to our newsletter!

    More from our blog

    See all posts

    Leave a Comment