Previously, I used the following method to force the browser to reload my JavaScript file if there was a new version available.
<script src="common.js?version=1337"></script>
<script src="app.js?version=1337"></script>
My HTML is automatically generated (e.g. with PHP), so this is easy to automate.
Now I want to use ES6 modules and import my common code. My HTML becomes:
<script src="app.js?version=1337" type="module"></script>
And app.js
contains the import:
import {foo, bar} from './common.js';
Now my question: how do I influence the caching of common.js
in the new scenario?
I don't want to manually edit app.js
every time I edit common.js
. I also don't want to dynamically generate/pre-process any of my JavaScript files, if possible.
Modules are cached after the first time they are loaded.
You can cache a resource using three methods add , addAll , set . add() and addAll() method automatically fetches a resource, and caches it, whereas in set method we will fetch a data and set the cache. });});
Unlike mobile applications, a web browser doesn't allow to clear its cache memory. Though we cannot clear all cache of the client browser it is still possible to load the webpage without caching by using meta tags in the HTML code.
ES6 module loaders will be asynchronous while node. js module loaders are not.
Short Version:
Just use Webpack, and you can keep doing your trick because all the javascript will be in a single file.
Long Version:
You said you don't want to pre-process your javascript files. I would reconsider that stance. Most modern web applications (and their associated frameworks like React, Angular, Vue.js) are built using some sort of preprocessor/packager that bundles all the javascript for the app into one or more files.
There are many good reasons to do this that we don't need to re-iterate in full here, but briefly, you can do type-checking (e.g. TypeScript), linting, tree-shaking, optimization, obfuscation, and compacting easily.
Bundled javascript is often smaller (by a large margin), faster, and more correct. It leads to shorter loading times and less bandwidth usage, which is particularly important when so many more than 50% of web traffic is from mobile these days.
While it might be a bit of learning curve, it's the direction our industry is going, and with good reason. The reason there isn't an easy way to include a cache-busting query parameter in ES module important is probably because the designers of the language considered it an anti-pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With