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:
Top-level
await
will be enabled by default in Chrome (Chromium) 89! That means the code example doesn’t need the async wrapper function:Example pen:
https://codepen.io/trusktr/pen/gOwQPEN
We use it on our projects at work for code splitting as mentioned above, the change significantly improved performance all round and we are seeing huge results as we go back and roll it into older projects for clients.
I am thinking about dynamic language loader for client-side syntax highlighter.
Around 2010 I used to do “conditional loading” of jQuery plugins, using a very rudimentary and not at all bulletproof method — the logic was like this (and please forgive any syntax errors. I haven’t written jQuery for a long time):
That way, I could conditionally load stuff like image sliders, and avoid having them be part of a giant site.js file.
Thank you very much, I hope I can use it, I did not know confetti, it is perfect to check if the person is on a birthday and show