How to cache locally

Hello everyone, I exported my project and deployed it in my server. My project has 187M, and it took 3 minutes to load. I refreshed or reopened and found that it needs to be reloaded. Will this not be cached locally? :drooling_face:

The browser is responsible for caching. Generally, it won’t redownload files that it recently accessed

See: Understanding Browser Caching | Engineering Education (EngEd) Program | Section

You can also use the cache storage from the browser directly.
I use this to cache large GLB files, that are usually not cached by the browser because of their sizes.

A simplified (fully working) example would be:

async function fetchWithLocalCache(url) 
{
	try {
		const cache = await caches.open('MyLargeFileCache');
		const cachedResponse = await cache.match(url);

		if (cachedResponse) {
			// If a cached response is found, return it
			const blob = await cachedResponse.blob();
			return URL.createObjectURL(blob);
		} else {
			// If no cached response is found, fetch the resource
			const response = await fetch(url);
			
			// Cache the fetched resource for future use
			await cache.put(url, response.clone());

			const blob = await response.blob();
			return URL.createObjectURL(blob);
		}
	} catch (error) {
		console.error('Error downloading url:', error, url);
		// Handle any errors that occur during the process
		return null;
	}
}

Hope this helps.

1 Like