4

When we use lazy-loading for downloading specific web modules, e.g.:

import('./polyfills').then(render); 

Will the browser cache these dynamically loaded files and does webpack use the cached version on subsequent requests?

With bundle splitting I know the browser will cache the loaded files; I assume this should be the same for code splitting, but I'm not sure.

1 Answer 1

1

Cache-Control response header specifies if and for how long a resource can be cached. Your server is responsible for setting it.

When webpack-generated code encounters a dynamic import, it fetches and then executes it. Whatever is exposed by the module is then available as long as the page isn't closed/reloaded and when the same import is encountered again those in-memory bindings are used (the module isn't refetched or executed again).

Sign up to request clarification or add additional context in comments.

4 Comments

So when the user visits the site again, dynamically fetched components are not cached. Doesn't sound all that great, I don't understand what's the fuzz about code splitting. Unless I'm missing something, sounds like bundle splitting is way more useful. Browsers foresee caching, then code splitting undos the benefit for a very short term benefit (i.e. it is limited to the first initial pageload).
@Trace yes, the benefit is that you get faster initial page load but dynamic modules can be cached in the same way as code chunks when you do bundle splitting so subsequent visits use cached resources (basically, you get site's initial TTI faster at the cost a bit slower initial navigation between site segments). Bundle splitting prevents a user from redownloading the whole bundle even if you do a small code change. They can be used together.
But this contradicts what you wrote in your answer: Whatever is exposed by the module is then available as long as the page isn't closed/reloaded and when the same import is encountered again those in-memory bindings are used (the module isn't refetched or executed again). So in your comment you mention that you can cache these chunks. So which is it? Any resource that confirms this? Caching that I mean, is in the context of caching after page reload, not in memory.
@Trace a browser can cache a dynamic chunk (which is just a js file) like any other resource (guided by Cache-Control header) - it has nothing to do with webpack or javascript but it's controlled by the server that sets the header. webpack runtime deals with a dynamic import like I described in my answer: when encountered again it won't ask the browser for the imported module but will use in-memory bindings that it already created (which can be thought of as webpack cache similar to node module cache).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.