Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reload a dynamically loaded ES6 module (using import() as a function) without reloading the whole page?

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.com/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?

like image 420
Dmitry Avatar asked Jan 20 '26 02:01

Dmitry


1 Answers

You 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.

like image 193
Lajos Arpad Avatar answered Jan 21 '26 17:01

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!