Checkout my Getting Started with React video course on Skillshare. It is 100% free.

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.

Home Screencasts Best of Newsletter Search X