Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

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 "";

// make stuff with jquery

We can have:

const button = document.getElementById("btn");
button.addEventListener("click", e => {
    .then(module => window.$ = module.default)
    .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
    .then(module => {
        // stop loading indicator
        window.$ = module.default;
    .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