One of the Angular 17 awesome features shipped is the defer block which allows to lazy load components, directives and pipes, while configuring it on the template level via @defer
.
If you already know the theory and want to get your hands dirty with @defer
, here's an app you can see various usecases and combinations:
ducin.github.io/angular-defer
See how does application runtime and user interaction trigger @defer
and what certain bundles get loaded into the browser.
It includes:
⚡️ components, directives, pipes
⚡️ multiple triggers and their combinations
⚡️ practical usecases (🪗 accordion, 📦 npm package and many more)
⚡️ analyze with devtools
⚡️ explanations included
Usecases implemented:
⚡️ when condition: @defer (when isVisible) {...}
⚡️ on idle: @defer (on idle) {...}
⚡️ on viewport: @defer (on viewport) {...}
⚡️ on interaction: @defer (on interaction) {...}
⚡️ on hover: @defer (on hover) {...}
⚡️ on immediate: @defer (on immediate) {...}
⚡️ on timer: @defer (on timer(2000ms)) {...}
🪗 accordion: @defer (on hover(accordion); on timer(5s)) {...}
(before accordion section gets clicked)
👫 multiple deferrable
📦 npm package: <link rel="modulepreload" href="chunk-BYHJVGJ4.js">
🗃️ nested defer: @defer (on timer(2s)) { @defer (on interaction) {...} }
⏱️ prefetch: @defer (on interaction; prefetch on idle) {...}
🚚 loading vs placeholder: placeholder (minimum 500ms) {...}
& @loading (minimum 1s; after 10ms) {...}
💥 defer error: @error {...}
So open your browser devtools Network
tab and have a play with the interactive examples 💪
Follow me on twitter for more frontend (js, ts, react, angular etc.) deep dives!
Top comments (4)
hmm, this puts at least two articles of mine in the bin of history :/ nice going Angular people :)
@ayyash wasn't my intention! 🫣 Yeah, Angular is moving forward so nice!
Thanks for sharing. Deffer is a new syntax (at least for me) where I needed some time to wrap my head around it when to use it. Seems like (for me) the most appropriate places will be charts. Since charts may take some time to render, they can slow down the whole UI. I believe if you wrap them inside the
@deffer
block, the application should not be in the blocking state.@krivanek06 AFAIU your question, not necessarily.
@defer
block basically "cuts away" pieces (components, directives, pipes), as long as they're standalone (!) and move them away to another bundle (lazy loaded chunk).The main point is that your initial bundle size decreases, which is super useful for your LCP.
So yeah, charts would be a good example, but NOT because they take time to load and display anything. But perhaps an entire library would have to be loaded (c3, d3, whatever) which is not needed on the initial page.
It's basically lazy loading but on TEMPLATE level, NOT routing level.
PS you can either play the recorder video demo or check it out yourself - it's the lazy chunks (devtools network tab) which is the whole point. Initial bundle is smaller 🔥