The following code will always log the same message even if the module has changed on the server, regardless of Cache-Control headers sent:
import('.mjs').then(m => console.log(m.default))
unless the whole page is reloaded.
Is there a programmatic way to bust the dynamic import cache, similar to delete require.cache[...]
in NodeJS?
The following code will always log the same message even if the module has changed on the server, regardless of Cache-Control headers sent:
import('http://example./script.mjs').then(m => console.log(m.default))
unless the whole page is reloaded.
Is there a programmatic way to bust the dynamic import cache, similar to delete require.cache[...]
in NodeJS?
-
Do you call
import
once? Normally when the module gets updated you should executeimport('http://example./script.mjs')
again. – Anton Tuyakhov Commented Oct 18, 2019 at 15:46 - Calling it again does not reload the module unless the whole page is refreshed. Try it in devtools. It makes sense usually since modules may have global singletons the rest of your code might rely on: same behavior as Node's require. However in Node you can manually bust it if you want. – Dmitry Commented Oct 18, 2019 at 22:47
- 3 Modules are cached by URL and I don't think there isn't currently a way to invalidate that cache. Would it be feasible to have a random querystring on your script when loading dynamically? – loganfsmyth Commented Oct 19, 2019 at 0:58
- That's indeed the only solution I found so far, but it also prevents the server from sending 304s when the script has actually not changed – Dmitry Commented Oct 19, 2019 at 2:36
-
2
@Brad There's not; if anything, the ECMAScript specification requires that the same module identifier always resolves to the same module. At best, import attributes could affect this (as they are part of the cache key), i.e. a solution like
import('…', {with: {version: Date.now()}})
would be allowed. But I know of no loader standard or implementation that does use this. – Bergi Commented Apr 14 at 20:14
2 Answers
Reset to default 1You can add a random querystring to the URL to avoid it being cached. It would make sense to have an API endpoint at your server that would get the timestamp of the last change of the script. So you could send a request to this API endpoint and if the timestamp turns out to be newer than the latest load of the file, then you could add a random querystring and import it.
To avoid browser cache you should make script url dynamic. There will be some overhead to get dynamic part of url (hash or query) from server. But you will have wanted behaviour, no page reload and script refetch.
The advanced approarch is hot-module-replacement (HMR
), for example in webpack https://webpack.js/concepts/hot-module-replacement/.
But webpack HMR
is not for production usage, only for dev purpose.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745612367a4636025.html
评论列表(0条)