How to Returns whether the webpage was cached by the browser in JavaScript ?


In JavaScript, we can check whether the webpage was cached by the browser using the caches API and the match method. Here are the steps to do it:

Method 1: Using the caches API

  • Check if the caches API is available in the browser:
if ('caches' in window) {
  // caches API is available
}
  • Use the caches.match() method to check if the webpage is cached:
if ('caches' in window) {
  caches.match(window.location.href).then(function(response) {
    if (response) {
      // webpage is cached
    } else {
      // webpage is not cached
    }
  });
}

The caches.match() method returns a Promise that resolves to the cached response, if available, or undefined if not.

Method 2: Using the performance API

  • Check if the performance API is available in the browser:
if ('performance' in window) {
  // performance API is available
}
  • Use the performance.getEntriesByType() method to check if the webpage is cached:
if ('performance' in window) {
  var entries = performance.getEntriesByType('navigation');
  if (entries.length > 0) {
    var entry = entries[0];
    if (entry.transferSize === 0 && entry.encodedBodySize === 0) {
      // webpage is cached
    } else {
      // webpage is not cached
    }
  }
}

The performance.getEntriesByType() method returns an array of performance entries of a given type. In this case, we are using the 'navigation' type to get information about the current webpage. The entry.transferSize and entry.encodedBodySize properties are both 0 if the webpage was loaded from cache.

Example:

if ('caches' in window) {
  caches.match(window.location.href).then(function(response) {
    if (response) {
      console.log('Webpage is cached');
    } else {
      console.log('Webpage is not cached');
    }
  });
}

if ('performance' in window) {
  var entries = performance.getEntriesByType('navigation');
  if (entries.length > 0) {
    var entry = entries[0];
    if (entry.transferSize === 0 && entry.encodedBodySize === 0) {
      console.log('Webpage is cached');
    } else {
      console.log('Webpage is not cached');
    }
  }
}


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.