Service Worker - не удалось получить файлы - PullRequest
1 голос
/ 18 июня 2020

Сервисный работник интегрирован в приложение. При запросе CSS Poppins-Regular.ttf работник файлового сервиса не отправляет кэшированный файл. Консоль «выдает» ошибку FetchEvent для [url] привел к ответу с сетевой ошибкой Ошибка консоли

Но файлы кэшируются вместе с другими файлами при запуске приложение впервые Кэшированные файлы

Вот код файла CSS, в который я добавил файлы шрифтов


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

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

Вот сервис код работника

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;
});

Что мне делать, чтобы исправить эти ошибки? Любая помощь приветствуется.

1 Ответ

0 голосов
/ 24 июня 2020
  1. Измените caches.match(event.request) на caches.match(event.request, { ignoreSearch: true })
  2. Убедитесь, что запрашиваемый URL совпадает с URL в кеше ('/inv/fonts/Poppins-Medium.ttf')

От developer.mozilla.org

ignoreSearch : логическое значение, указывающее, следует ли игнорировать строку запроса в URL-адресе. Например, если установлено значение true, часть ?value=bar из http://example.com/?value=bar будет игнорироваться при выполнении сопоставления. По умолчанию false.

.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...