astrolicious / astro-tips.dev

The place for content that goes beyond the official docs, for all Astronauts!

Home Page:https://astro-tips.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Dynamic imports in scripts

OliverSpeir opened this issue · comments

Here's a nice write up for it by Chris on discord

This can be thought of like client:idle for vanilla js and one could even be made for client:visible with intersection oberserver

Right, the browser’s preload scanner will go through parsing your HTML deciding what to download.

For scripts like those above, they may very likely end up as stuff like this in the :
<script type="module" src="/_astro/hoisted.Ozp4WWO7.js"></script>

The browser will find that pretty early on, and decide it needs to download /_astro/hoisted.Ozp4WWO7.js, potentially immediately.

So if the <script> used a static import X from 'x', that would come along with that initial download (most likely bundled as part of the same file).

By using a dynamic import() instead, the imported module is only downloaded once the script actually executes (we’re basically splitting the bundle into two bits and delaying the download of the dependency).

<script>
window.addEventListener('DOMContentLoaded', async () => {
  const { something } = await import('module-i-need');
  something();
}, { once: true });
</script>
<script>
const { something } = await import('module-i-need');
something();
</script>

Note

I’d be careful about doing this too often — there’s a reason bundlers bundle stuff. But for larger deps that aren’t needed for essential functionality it’s a helpful trick to do stuff lazily. But get it wrong and delay downloading something critical then that’s horrible for perf.

  • Chris

Use case

  • Conditional Loading: Modules can be conditionally loaded based on certain runtime conditions (like feature flags or user preferences).
  • very Lazy Loading: Components or features that are not immediately necessary can be loaded later, improving initial load times.

Impact

  • Network requests for imported code delayed until they are used
  • Improve initial page load performance
  • Code execution might take slightly longer as when the dynamic imported code is used it will have to download then instead of being downloaded right away

Could you add a potential use case for it in the issue description?

Could you add a potential use case for it in the issue description?

done