Skip to content
Dynamic import js

Dynamic imports in JavaScript

Unlike static imports, we can dynamically import JavaScript files as needed. Most modern frameworks and build tools use this feature to optimize the amount of script loaded on the client-side. In this post, we will explore how to use the dynamic import feature and optimize our imports.

Code splitting in JavaScript

A huge chunk of code can result in a bad developer experience as the code becomes difficult to modify and maintain. This was solved when the concept of modules was introduced in ES6 (ES2015) using which we can split huge chunks of code into small modules that are easy to maintain and be used when needed.

Static import

In a static import, we import the required .js files and utilize their functions as per need. However, this may not be efficient in all cases as some JavaScript modules can be humongous, and importing more of them can affect the performance. Imagine loading a 100KB file over a slow network and not using it at all.

import * as myModule from './myModule.js';

In our code we’ll load some initial scripts and then import many modules, however, it’s not guaranteed that we will utilize all the imported modules. We might wanna use them based on a certain condition or a function call based on the user’s action. Using dynamic imports we could save both time and bandwidth.

Dynamic import

The fundamental concept behind dynamic imports is to import JavaScript modules dynamically as per our needs. We can import modules based on an if condition or a function call or an event.

// Syntax for dynamic import
import('myModule')
    .then((myModule) => /* Do something */ )
    .catch((error) => /* fallback */ );

The dynamic import() actually returns a promise, therefore it’s thenable we can use .then(), async/await methodology. The best part is that the syntax is the almost same as static imports.

async function loadModule() {
    const myModule = await import('./myModule.js');
    // utlize the module
}

Note 📝: Although the import() looks like a function call it is the syntax itself. Hence we shouldn’t try to call/apply or assign import directly to a variable.
Reference ~ v8blog

Applications

  • Code splitting
  • Conditionally import modules
  • Save page load time by dynamically importing dependencies

Support: All modern browsers support this feature

Conclusion

The dynamic import feature was part of the ES2020 release and is now supported by all modern browsers. I believe we can use this feature along with static import. First, we static import all the main scripts and then dynamically import other dependencies like comments, analytics. What are your thoughts on this feature?