Hello, guy's let's hunt what is dynamic import in JavaScript?
Dynamic Imports
The standard import syntax is static and will always result in all code in the imported module being evaluated at load time. In situations where you wish to load module conditionally or on-demand, you can use a dynamic import instead.
To dynamically import a module, the import keyword may be called as a function. When used this way, it returns a promise.
import('/modules/my=moudle.js')
.then((module) => {
// Do something with the module π
});
- This form also supports the await keyword.
let module = await import('/modules/my-module.js');
Note: Dynamic imports ES 2020 (ES 11) feature is fully supported by Chrome 63+, Firefox 67+, Safari 11.1+ and NodeJS 13.2.0 (By importing either commonJS or ES module files)
When to use Dynamic Imports?
- Loading code in demand
button.addEventListener('click', event => {
import('dialogBox.js')
.then(dialogBox => {
dialogBox.open();
})
.catch(error => {/* Error Handling */})
});
- Conditional loading of modules
if (isLegacyPlatform()) {
import(...)
.then(...);
}
- Computed module specifiers
import(`messages_${getLocale()}.js`)
.then(...);
Why to use Dynamic Imports?
- When importing statically, it significantly slows the loading of your code and there is a low likelihood that you will need the code your are importing, or you will not need it until a later time.
- When importing statically, it significantly increases your program's memory usage and there is a low likelihood that you will need the code you are importing.
- When the module you are importing does not exist at load time.
- When the import specifier string needs to be constructed dynamically. (Static import only supports static specifiers)
- When the module being imported has side effects, and you do not want those side effects unless some condition is true. (It is recommended not to have any side effects in a module, but you sometimes cannot control this in your module dependencies)
βThanks For Reading | Happy Scripting π
Get weekly newsletter of amazing articles I posted this week and some offers or announcement. Subscribe from Here
Discussion (15)
Is that button at the end embedded, or is it an actual inline button? If it's the latter, how did you do it?
Also, on topic, nice descriptive post.
It's not embedded and not the inline one.
Then how did the button get there?
It's an image πΆ
Oh. Then how did you attach a href to it? I didn't know you could do that on DEV.
you can put it inside of an
<a>
tag I believe.Exactly
Simple coding bruh!!
We all make mistakes...
Agreed
The tf happened here while I was gone?
Nothing π
Can you also do this in MDF?
yup