Lazy loading amCharts modules

It is possible to load the amCharts library only when needed. This tutorial will explain how.

The import() expression is the official way to lazy load any ES6 module, including amCharts.

However, import() can only import a single module, so you have to combine it with Promise.all to load multiple modules. Here is how to do that:

Promise.all([
import("@amcharts/amcharts4/core"),
import("@amcharts/amcharts4/charts"),
import("@amcharts/amcharts4/themes/animated")
]).then((modules) => {
const am4core = modules[0];
const am4charts = modules[1];
const am4themes_animated = modules[2].default;

// Chart code goes here
}).catch((e) => {
console.error("Error when creating chart", e);
})

The above code loads three amCharts modules, and when they are done loading it then runs the (modules) => { ... } function.

This loading happens asynchronously, and the modules are loaded in parallel, so it's very efficient!

Each module in the Promise.all array gets put into the modules array, in the same order:

  • modules[0] is the "@amcharts/amcharts4/core" module
  • modules[1] is the "@amcharts/amcharts4/charts" module
  • modules[2] is the "@amcharts/amcharts4/themes/animated" module

You can also use this to lazy load your own modules!

Here is a working example in Angular. It takes a while to load in CodeSandbox, but it will load much faster in your real app.

The import() expression works natively in every browser except Edge and IE.

Webpack also has built-in support for import(), which allows you to use it in all browsers (including Edge and IE).