In another post, I wrote about reading the contents of an external file with JavaScript. A method that allows us to easily extract the data from a file.
While fetch
is a great method, it still requires a network request. Therefore, receiving the data locally, without sending an HTTP request, will probably result in better performance.
So in this post, we will cover how fetch
requests can be cached using JavaScript so that each network request is executed only once. We can then serve it directly from the local memory for future requests.
Scenario
Suppose we have a dropdown field where the user can choose from a number of options. Each selection will trigger the fetchFile
js function.
<select id="file-dropdown" onchange="fetchFile(this.value)">
<option value="">Select file</option>
<option value="file-a">File A</option>
<option value="file-b">File B</option>
<option value="file-c">File C</option>
</select>
Selecting the File A
option will bring up the contents of file-a.html
, selecting the File B
option will bring up the contents of file file-b.html
, etc.
Without caching
- User selects
File A
»file-a.html
is fetched. - User selects
File B
»file-b.html
is feteched. - User selects
File A
»file-a.html
is fetched again.
As we can see, in the described scenario with no caching, file-a.html
will be fetched twice. In fact, any of the files will be fetched again each time the selection changes.
With caching, however
- User selects
File A
»file-a.html
is fetched and cached. - User selects
File B
»file-b.html
is fetched and cached. - User selects
File A
»file-a.html
is served from the local memory.
In terms of code
let files = {};
function fetchFile(selectedOption) {
if (!selectedOption) {
return;
}
if (files[selectedOption]) {
// The HTML code of this file has already been fetched.
// It is available as 'files[selectedOption]'.
theRestOfTheCode();
} else {
// Fetch the HTML code of this file.
fetch('/assets/files/' + selectedOption + '.html')
.then((resp) => resp.text())
.then(function (data) {
// Save the HTML code of this file in the files array,
// so we won't need to fetch it again.
files[selectedOption] = data;
// The file is now available as 'files[selectedOption]'.
theRestOfTheCode();
});
}
}
We create an empty files
array that will store all cached files.
In the fetchFile
function, we first check if this file has already been fetched. If so, we can just skip to the rest of the code (theRestOfTheCode()
function).
However, if the file doesn’t exist in the files
array, this means that this option was selected for the first time. In this case, we need to fetch
it and cache it so that it will be available locally the next time. We can then proceed as usual to the rest of the code.