Boosting Web App Performance with Effective Caching Techniques
Written on
Chapter 1: Understanding Caching in Web Development
Recognizing potential issues in your code and swiftly addressing them is a significant marker of growth as a developer. Recently, I encountered such a scenario in a project I was working on. Implementing caching can significantly minimize the number of network requests your application makes, leading to a notable enhancement in speed and overall performance.
Interested in exploring more? Here are several methods to incorporate caching into your application.
Section 1.1: Utilizing the Cache API
The Cache API is a browser-based tool that enables you to locally store and retrieve data from an API, acting as your cache. This API allows for saving various data types, including HTML pages, JavaScript files, images, and more.
// Check for Cache API support
if ('caches' in window) {
var cacheName = 'myCache';
// Open or create a cache with the specified name
caches.open(cacheName).then(function(cache) {
.then(function(response) {
if (response.ok) {
var responseClone = response.clone();}
})
.catch(function(error) {
console.error('Error fetching data:', error);});
});
// Retrieve data from the cache
if (cachedResponse) {
cachedResponse.json().then(function(data) {
console.log('Data from cache:', data);});
} else {
console.log('Data not found in cache. Fetching from the server...');}
});
} else {
console.error('Cache API is not supported in this browser.');
}
Section 1.2: In-Memory Caching with JavaScript Map
Using JavaScript Maps for caching is a straightforward technique where you associate keys with values, allowing the map to function as an in-memory cache. This is the method I frequently employ in my projects.
The concept is simple: link a data point to a unique identifier (like an ID) and store it in a Map object. Before making any calls, check if the value exists in the Map. If it does, retrieve it; if not, proceed with an API call.
const cache = new Map();
function fetchData(url) {
console.log(Fetching data from ${url});
return new Promise(resolve => {
setTimeout(() => {
const data = { result: Math.random() };
resolve(data);
}, 1000);
});
}
async function getData(url) {
if (cache.has(url)) {
console.log(Data found in cache for ${url});
return cache.get(url);
}
const data = await fetchData(url);
cache.set(url, data);
return data;
}
.then(result => console.log('Result:', result))
.catch(error => console.error('Error:', error));
Chapter 2: Advanced Caching Strategies
The first video, "How to use Browser caching to improve the Performance of your web application," explores various caching techniques to enhance web app performance.
Section 2.1: Implementing LRU Cache
The final method to implement caching in JavaScript is through specialized libraries or frameworks designed for this purpose. A popular choice is the lru-cache (Least Recently Used Cache) library, which offers an efficient caching mechanism.
const LRU = require('lru-cache');
const cache = new LRU(100);
function fetchData(url) {
console.log(Fetching data from ${url});
return new Promise(resolve => {
setTimeout(() => {
const data = { result: Math.random() };
resolve(data);
}, 1000);
});
}
async function getData(url) {
const cachedData = cache.get(url);
if (cachedData) {
console.log(Data found in LRU cache for ${url});
return cachedData;
}
const data = await fetchData(url);
cache.set(url, data);
return data;
}
.then(result => console.log('Result:', result))
.catch(error => console.error('Error:', error));
The second video, "This is why you need caching," explains the importance of caching and how it can significantly impact the performance of web applications.