DEV Community

Cover image for πŸš€ Dynamic Imports (Code Splitting) | ES2020

πŸš€ Dynamic Imports (Code Splitting) | ES2020

Niall Maher on May 21, 2020

The ES2020 features were just approved by the TC39 committee, and in the proposal, you can import a file dynamically. What does that mean? Inst...
Collapse
 
jwp profile image
JWP β€’

excelente, mi amigo!

Collapse
 
nialljoemaher profile image
Niall Maher β€’

Gracias! πŸ’œ

Collapse
 
natterstefan profile image
Stefan Natter πŸ‡¦πŸ‡ΉπŸ‘¨πŸ»β€πŸ’» β€’

Thanks Niall!

Collapse
 
nialljoemaher profile image
Niall Maher β€’

No problemo! πŸš€

Collapse
 
kryptand profile image
Kryptand β€’

Hello Niall, thank you for that interesting article.

The example you posted would only be valid if you use the await in an async function context-
document.getElementById("button")
.addEventListener("click", async() => {
const { app } = await import("./app.js");
app();
});

Collapse
 
starboysharma profile image
Pankaj Sharma β€’

I am wondering if a user clicks a button ten times which means we are going to import app.js each time. So, it will affect app performance or not? πŸ˜…πŸ€”

Collapse
 
nialljoemaher profile image
Niall Maher β€’

Good question, it will be available in the browser memory. By clicking it again you don't reload it. It's smart enough to know it has the bundle loaded so it will no longer need to be fetched from the web after the initial load. So it won't negatively affect your performance. πŸš€

Thread Thread
 
gorvgoyl profile image
Gourav β€’

are you sure? don't we need to check first for undefined and then load the module

if(!app)
{
app = await import("./app.js");
}

Thread Thread
 
nialljoemaher profile image
Niall Maher β€’

You could wrap the whole thing in a try catch if you wanted some error checking. This is just a super simplified sample.

Thread Thread
 
gorvgoyl profile image
Gourav β€’

no this is not about error checking.. if we check beforehand that the module is already loaded then we need not load it again

Thread Thread
 
nialljoemaher profile image
Niall Maher β€’

Nope, run the code with the network tab open and you'll see it's only fetched once no matter how many times you click the button.

Thread Thread
 
gorvgoyl profile image
Gourav β€’

got it, if that's the case then it's okay.

Collapse
 
nialljoemaher profile image
Niall Maher β€’

Good catch! A typo on my behalf. Thank you πŸ’œ

Collapse
 
djamaile profile image
Djamaile β€’

Can we already use this natively?

Collapse
 
nialljoemaher profile image
Niall Maher β€’

There is some pretty good support already yes:
caniuse.com/#feat=es6-module-dynam...

Collapse
 
rcsm profile image
Rafael Cascalho β€’

Wow, pretty cool! Nice article Niall, congrats :)

Collapse
 
nialljoemaher profile image
Niall Maher β€’

Cheers Rafael!