šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

You can dynamically import Javascript modules

A big performance gain we can implement is to load Javascript modules only when they are needed.

So, instead of having a top default declaration like this:

import * from "https://cdn.skypack.dev/jquery";

// make stuff with jquery

We can have:

const button = document.getElementById("btn");
button.addEventListener("click", e => {
  import('https://cdn.skypack.dev/jquery')
    .then(module => window.$ = module.default)
    .then(makeBgOrangeWithJquery)
    .catch(err => { alert(err) });
});

const makeBgOrangeWithJquery = ()=> {
  $("body").css("background-color", "orangered");
}

A full working codepen can be found below.

See the Pen
dynamically import
by JS Craft (@js-craft)
on CodePen.

You can even use it with something like a loading indicator.

button.addEventListener("click", e => {
    // set loading indicator
    import('https://cdn.skypack.dev/jquery')
    .then(module => {
        // stop loading indicator
        window.$ = module.default;
    })
    .then(makeBgOrangeWithJquery)
    .catch(err => { alert(err) });
});

Of course, if all your page is dependent upon a library like jQuery or React will not make too much sense to dynamically import that library.

But there are cases when you have a component like a complex video player that can use a lot of js, and that video will start only when the user clicks on it. Well in a case like this, the user may not even ever click the play button so it makes sense to include that module only when needed.

A nice article to read about this article written by Addy Osmani. Also you may want to check the defer and async attributes when loading scripts.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

Your email address will not be published. Required fields are marked *