Dynamic imports of Javascript modules.

Dennis Bauszus
2 min readOct 7, 2021

--

Proposed at TC39, an import function is finally available in most browsers. While this is not a feature to make everyday developer life easier it allows for some interesting solutions. In this shortish article I want to highlight a particular use case for dynamic imports.

You may skip this article if you need to support Internet Explorer.

When to use dynamic imports?

MDN advises to use dynamic imports only when necessary. Modules to support optional features which may not be required to launch an application are suited for dynamic imports.

We are building a location intelligence library (MAPP). Openlayers is the primary application interface for spatial data and is required at initialisation in order to present the data as a map control.

Location data may also be presented as chart or table. For this we require additional libraries such as Chart.js or Tabulator. In order to keep the MAPP package lean we prefer to not bundle additional libraries over a size of ~5kb. Chart.js and Tabulator may be provided as script tags in our application views. These libraries may not be required at all by an application view, or may only be required at a later stage. It is now possible to import these modules just in time when needed.

How to use dynamic imports?

We create our own small modules to be imported for all optional modules. Since the import function returns a promise, our exported function must be async to be awaited for the import to resolve.

The imported module is stored in a variable outside the closure of our export and shared between multiple imports of the same module.

If null when required, the dynamicImport method will check whether the module has already been assigned to the window (global) object via a script tag. The module assigned to the window will be assigned to our variable if this is the case. Otherwise we will await the import function to resolve the Tabulator module from skypack.

Disclaimer

This is a fairly new way of doing things. We are currently undergoing a major re-write of the XYZ ecosystem and specifically the MAPP frontend. We are planning to retire Webpack in favour of Snowpack and are re-thinking our handling or third party modules in this regard. We are NOT using this technology yet in production and would like to read your comments.

For all things Mapp, XYZ, and Location Intelligence in general please follow GEOLYTIX on all channels.

--

--

Dennis Bauszus

I am doing some web and map stuff with @GEOLYTIX. Mostly maps on the web.