Connect with us

Article

Dynamic, Conditional Imports

Published

on

Dynamic, Conditional Imports


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/[email protected]"
    );
    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:



Source link

Continue Reading
Click to comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.