Lazy-loading React components with webpack 2+ dynamic import and code-splitting

preview_player
Показать описание

As mobile device or low bandwidth users may suffer from long initial load-times, a consequence of bundling heftier dependencies into a single source bundle, it is ideal to defer and progressively enable—or to prefer on-demand loading—of functionality where possible. If a dependency incurs 5mB of final bundle size but the core UI functionality can afford to instead 'fire and forget', continuing loading in the background while the user proceeds through some initial stage of interface unblocked, then we have achieved a better overall experience. With any luck, the user will have finished this progressively loading of any 'deeper' functionality by the time they've navigated there.

In this video we utilise an async function to 'await' a deferred component before storing and rendering it, using its absence to show some non-ideal state; the example concludes by changing this behaviour to load the chunk if not already loaded, and store+render the React component on button press.

Рекомендации по теме
Комментарии
Автор

Thanks for the code example, it's exactly what I am looking for

maoyulore
Автор

Had couple of doubts.
I'm actually looking for something similar for dynamic layout templating where I'm planning to import components dynamically as per the JSON.(could also work as a part of code splitting)

1. How does this work for server side rendering.

2. Does dynamically imported component gets chunked in to a separate Js file with Webpack 2, and gets referenced internally( gets called with in app.js or it should be externally included )

Can you suggest how to proceed further that would help.

naveenn
Автор

Also, is there another way to make this dynamic import into the parent component other than storing it into its state ? Is this the ideal way to work with when dealing with large scale application and any state management frameworks like redux?

Автор

great tutorial! thank you so much. I have a quick question. the lazily loaded component's bundle which is loaded to browser, where in the code is the app making that call to grab that lazily loaded bundle from the server? Or did I misunderstand the actual workflow here? Your response is very helpful.