You can dynamically import Javascript modules

šŸ“– Neural networks for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!

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 for Javascript developers

The Neural Networks for JavaScript developers book is almost ready! Learn the basics of AI with TensorFlowJs examples. Join now the presale and get a 15$ coupon off the launching price!


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

Neural Networks for JavaScript developers
Presale - 15$ free coupon

Hi friend! Before you go, just wanted to let you know that in March 2023 I will be launching the TensorFlow.Js by Example course.

This course will include basic concepts of AI and Neural Networks done with TensorFlowJs such as:

  • Working with datasets
  • Visualizing training
  • Deep Neural Networks in JavaScript
  • Reinforcement Learning
  • Convolutional neural networks
  • and much more ...

Also, there will be a lot of examples as:

  • Object detection
  • Natural language processing
  • Face and voice recognition
  • Gaming AI

Join now the waiting list and get a 15$ coupon off the launching price!

X