Vishi
Vishi

Reputation: 9

Service Worker - Failed to fetch files

Service worker is integrated in the app. When CSS requested Poppins-Regular.ttf file service worker doesn't send the cached file. Console "throws" error The FetchEvent for [url] resulted in a network error response Console Error

But the files are getting cached along with other files when I run the app for the first time Cached Files

Here is the code of the CSS file where I have added the font files


@font-face {
    font-family: Poppins-Regular;
    src: url('../fonts/Poppins-Regular.ttf');
}

@font-face {
    font-family: Poppins-Medium;
    src: url('../fonts/Poppins-Medium.ttf');
}

Here is the service worker code

const __cacheName = 'MyCache';
const __precacheResources = [
    
    //fonts
    '/inv/fonts/Segoe-UI.ttf',
    '/inv/fonts/Segoe-UI-Bold.ttf',
    '/inv/fonts/Poppins-Medium.ttf',
    '/inv/fonts/Poppins-Regular.ttf',

];

var isFileLoadFinished = false;

self.addEventListener('install', event => {
    isFileLoadFinished = false;
    console.log('Service worker :', __sw_version, 'is installed!');
    self.skipWaiting();
    caches.delete(__cacheName);

    event.waitUntil(
        caches.open(__cacheName)
            .then(cache => {
                return cache.addAll(__precacheResources)
                    .then(() => {
                        isFileLoadFinished = true;
                    })
            })
    );
});

/*
    this will send the object to the client via a message
    @param {msg_} is an object to send to 
    @return null
*/
function sendMessagetoClients(msg_) {
    console.log('sending msg to client. msg id is:', msg_.id)
    self.clients.matchAll({
        includeUncontrolled: true,  //returns only the service worker clients controlled by the current service worker. The default is false.
        type: "all"// "window"
    }

    ).then(clients => {
        if (clients.length == 0) {
            console.log('No clients');

        }
        clients.forEach(client => {
            console.log('the client is ', client);
            client.postMessage(msg_);
        });
    });
}

self.addEventListener('activate', event => {
    console.log('%s : Service worker :', (new Date()).toISOString(), __sw_version, ' is active! ');
    sendMessagetoClients({
        id: 002,
        msgText: 'All items loaded',
        data: isFileLoadFinished
    });
});

self.addEventListener('fetch', event => {
    event.respondWith(caches.match(event.request)
        .then(cachedResponse => {
            if (cachedResponse) {
                return cachedResponse;
            }
            return fetch(event.request).catch(err => {
                console.error(err);
            });
        })
    );
});

self.addEventListener('message', event => {
    console.log('%s : message received. msg id : %s', (new Date()).toISOString(), event.data.id);

    //process the msg
    if (event.data.id) {
        if (event.data.id == 001) {
            sendMessagetoClients({
                id: 002,
                data: isFileLoadFinished
            })
        } else if (event.data.id == 003) {
            sendMessagetoClients({
                id: 004,
                data: __sw_version
            })
        }

    }
    return;
});

What should i do to fix those errors? Any help would be appreciated.

Upvotes: 0

Views: 945

Answers (1)

Mohammadreza
Mohammadreza

Reputation: 11

  1. Change caches.match(event.request) to caches.match(event.request, { ignoreSearch: true })
  2. Make sure if the requested URL is the same as the URL in the cache ('/inv/fonts/Poppins-Medium.ttf')

From developer.mozilla.org

ignoreSearch: A Boolean that specifies whether to ignore the query string in the URL. For example, if set to true the ?value=bar part of http://example.com/?value=bar would be ignored when performing a match. It defaults to false.

Upvotes: 1

Related Questions