Friday, January 7, 2022

Conditional async import in JavaScript

In this post I am going to talk about conditional import module in JavaScript ( ECMAScript modules ).

The import statemen in JavaScript is static and therefore has two limitation:

  1. a module identifier cannot be constructed at runtime
  2. have to be declared at the top level of file and therefore cannot be nested within control flow statement like if statement.

In case you need conditional import you can use async dynamic import. Async import can be performed at runtime using special import() function.

The module identifier can be any module identifier supported by static import.

Let see example:

This form also supports the await keyword:

No comments:

Post a Comment