Chisom Kanu
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Cache API in JavaScript ## Introduction to Cache API [Caching](https://www.techtarget.com/whatis/definition/caching) involves storing frequently accessed data in a fast-access storage medium, such as memory, so that subsequent requests for the same data can be served quickly without having to go through the full process of retrieving it from the original source. [Cache API](https://web.dev/cache-api-quick-guide/#:~:text=The%20Cache%20API%20is%20a,storing%20data%20for%20later%20use.) is a [browser API](https://www.educative.io/answers/what-are-browser-apis#:~:text=Browser%20APIs%20are%20APIs%20that,managing%20client%2Dside%20storage) that provides developers with a way to store and retrieve data in a cache. It was first introduced in 2015 as part of the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API), which allows web developers to write scripts that run in the background of a web page and interact with the browser's network requests. The Cache API allows developers to cache web resources, such as [HTML](https://www.w3schools.com/html/) pages, [JavaScript](https://www.w3schools.com/js/) files, images, and other assets, so that they can be accessed quickly and efficiently. It is useful for progressive web applications ([PWAs](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps)), which rely heavily on caching to deliver fast and responsive user experiences. In web development, performance is an important aspect for a positive user experience. One way to improve performance is by using the Cache API in JavaScript. This [API](https://www.techtarget.com/searchapparchitecture/definition/application-program-interface-API) allows developers to store web resources like images, fonts, and scripts in the user's browser cache, reducing server requests and improving load times. It provides a simple interface for storing and retrieving network resources, together with the ability to manage and delete resources from the cache. In this article, you will learn how to use the Cache API to store and retrieve resources from the cache. ## Checking for Cache API Support The Cache API is supported in most modern browsers, including [Chrome](https://en.wikipedia.org/wiki/Google_Chrome), [Firefox](https://en.wikipedia.org/wiki/Firefox), [Safari](https://en.wikipedia.org/wiki/Safari_(web_browser)), and [Edge](https://en.wikipedia.org/wiki/Microsoft_Edge). Before using the Cache API, it's important to check if the browser supports it. To check if the browser supports the Cache API, we can use the code below: ```javascript if ('caches' in window) { // Cache API is supported //You can add your code here } else { // Cache API is not supported } ``` The code above checks if the `caches` object is available in the global `window` object. If it is, then the browser supports the Cache API. Note: The Cache API is not always available in every browser or environment. Some reasons why the Cache API may not be available are: * Browser Settings * Security Restrictions * Browser Support In cases where the Cache API is not available, developers can use other [caching mechanisms](https://www.geeksforgeeks.org/what-is-the-caching-mechanism/) such as [local storage](https://www.pcmag.com/encyclopedia/term/local-storage), to store data on the [client-side](https://elementor.com/resources/glossary/what-is-the-client-side/). They can also use [server-side](https://www.lawinsider.com/dictionary/server-side) caching solutions, such as [Redis](https://redis.io/), to store data on the server-side. Another option is to use a[ third-party library](https://support.cchifirm.ca/en/content/cch_ifirm/ifirm_3rdpartylibrairies.htm) that provides a similar caching mechanism that is compatible with a wide range of browsers. These libraries can help bridge the gap between different browsers and environments. It is always a good idea to provide fallback options for users who don't have access to the Cache API or other caching mechanisms. This could involve using default values or retrieving data from the server if the cache is unavailable. Also, use proper error handling techniques, such as logging errors to the console. ## Opening a Cache To open a cache, we use the `caches.open() ` method. This method takes a string as a parameter, which represents the name of the cache we want to open. If the cache does not exist, it will be created. Here's an example: ```javascript caches.open('my-cache').then(function(cache) { // Cache opened successfully }).catch(function(error) { // Failed to open cache }); ``` Here, the code opens a cache named `my-cache` and returns a promise that resolves with the cache object if successful. If an error occurs, the promise is rejected with an error object. ## Adding resources to the Cache There are three (3) ways to add resources to the cache, they are: * [Cache.add()](https://developer.mozilla.org/en-US/docs/Web/API/Cache/add) * [Cache.addAll()](https://developer.mozilla.org/en-US/docs/Web/API/Cache/addAll) * [Cache.put()](https://developer.mozilla.org/en-US/docs/Web/API/Cache/put) Let's go over each of these methods. ### Cache.add() In this method, `Cache.add() ` takes a [URL](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL) as an argument and adds the response from that URL to the cache. If the response is already in the cache, the method does nothing. For example: ```javascript caches.open("my-cache").then((cache) => { cache .add("/api/data") .then(() => console.log("Data added to cache.")) .catch((error) => console.error("Error adding data to cache:", error)); }); ``` In the code above, you open a cache named `my-cache` and then add the response from the URL `/api/data` to the cache. If the operation is successful, you log a message to the console. If there's an error, you log an error message instead. ### Cache.addAll() This method takes an array of URLs as an argument and adds the responses from those URLs to the cache. If any of the responses are already in the cache, the method skips them. ```javascript const urls = ["/api/data1", "/api/data2", "/api/data3"]; caches.open("my-cache").then((cache) => { cache .addAll(urls) .then(() => console.log("Data added to cache.")) .catch((error) => console.error("Error adding data to cache:", error)); }); ``` In the example above, you define an array of URLs and then open a cache named `my-cache`. You can now use the `Cache.addALL()` method to add the responses from the URLs in the array to the cache. If the operation is successful, you log a message to the console. If there's an error, you log an error message instead. ### Cache.put() The `Cache.put()` method works differently from the other methods; it takes a request object as an argument and adds the response from that request to the cache. If the response is already in the cache, the method overwrites it. Here's an example: ```javascript const request = new Request("/api/data"); caches.open("my-cache").then((cache) => { fetch(request) .then((response) => { cache .put(request, response) .then(() => console.log("Data added to cache.")) .catch((error) => console.error("Error adding data to cache:", error)); }) .catch((error) => console.error("Error fetching data:", error)); }); ``` In the code above, you create a new request object for the URL `/api/data` and then open a cache named `my-cache`. You now fetch the request using the `fetch() ` method and add the response to the cache using the `Cache.put() ` method. ## Retrieving resources from the Cache The Cache API provides two primary methods for retrieving resources from the cache: `match() `and `matchAll()`. The `match()` method is used to retrieve a single resource from the cache, while the `matchAll()` method is used to retrieve all the resources that match a given request. Here is an example of how you can use the `match()` method to retrieve a single resource from the cache: ```javascript caches.open("my-cache").then(function (cache) { cache.match("/path/to/resource").then(function (response) { if (response) { // Resource found in cache console.log(response); } else { // Resource not found in cache } }); ``` Here, you first open the cache using the `caches.open()`method, which returns a promise that resolves to the cache object. You then use the `match()` method on the cache object to retrieve the resource at the specified path. If the resource is found in the cache, the `match()` method returns a response object that can be used to access the resource. If the resource is not found in the cache, the `match()` method returns null. Below is an example of using the`matchAll()`method to retrieve all the resources that match a given request: ```javascript caches.open("my-cache").then(function (cache) { cache.matchAll("/path/to/*").then(function (responses) { if (responses.length > 0) { // Resources found in cache console.log(responses); } else { // No resources found in cache } }); ``` In this example, you use the `matchAll()` method to retrieve all the resources that match the pattern ``/path/to/*`` in the cache. The method returns an array of response objects that can be used to access the resources. If no resources are found in the cache, the `matchAll()` method returns an empty array. ## Deleting resources from the Cache When deleting resources from the cache, you use the `cache.delete() ` method. This method takes a request object as a parameter, which represents the [URL](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL) of the resource we want to delete. If the resource is found in the cache, it is deleted, and the method returns a promise that resolves to `true`. If the resource is not found in the cache, the method returns a promise that resolves to`false`. Here's an example: ```javascript caches .open("my-cache") .then(function (cache) { cache.delete("/path/to/resource").then(function (isDeleted) { if (isDeleted) { // Resource deleted successfully } else { // Resource not found in cache } .catch(function (error) { // Failed to delete resource from cache }); ``` This code deletes the resource at the URL `/path/to/resource` from the `my-cache` cache. If the resource is found in the cache, it is deleted, and the `isDeleted` parameter is `true`. ## Conclusion The Cache API in JavaScript, including checking for support, opening a cache, adding resources to the cache, retrieving resources from the cache, and deleting resources from the cache. By using the Cache API, you can reduce the time needed to fetch resources from the server and improve the overall user experience of your website. However, it's important to note that caching should be used carefully and selectively to avoid caching resources that may change frequently. With proper use, the Cache API can help create fast and responsive websites.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully