How to check if Response A has the same content as Response B in the browser?

37 views Asked by At

For offline PWA I want to do the following whenever a file / image is fetched using service workers:

  1. Serve file/image from cache
  2. Fetch that file/image from the network
  3. Check if the file/image from the network is different than that of the cache
  4. If it's different prompt the user if he wants to update using Confirm API

I need some advice on step 3

I have made code that checks if two responses have different contents by first representing the responses as an array of numbers and then checking if they have the same numbers at the same indices. I just wonder if this is a proper technique or if there is a better way of achieving this.

Here's the code:

    async function fetchAndCompareResponses() {
        const array1 = await getArray("/style.css")
        const array2 = await getArray("/style2.css")
        
        // gives false in this case because two files aren't the same
        const responsesAreTheSame = compareArrays(array1, array2)
        console.log(responsesAreTheSame)
    }

    function compareArrays (a, b) {
        // If the lengths differ, they can't be the same
        if (a.length !== b.length) return false

        // Check if the two arrays have the same elements at the same indices
        for (let i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                return false
            }
        }

        return true
    }

    async function getArray (url) {
        // Fetch response and convert it to an array
        const response = await fetch(url)
        const buffer = await response.arrayBuffer()
        return new Uint8Array(buffer)
    }

    fetchAndCompareResponses()

style.css:

    p {
        color: blue;
    }

style2.css which has a different color:

    p {
        color: green;
    }
0

There are 0 answers