@niknik_ykt
Не понимаю почему все это работает.

Как исправить ошибку кеширования?

Создал интернет магазин на OcStore 2.*. По задумке должна быть пвашка, но я третьи сутки получаю такую ошибку:
6447233377da3162429629.jpeg
Перелопатил весь интернет, выжал все возможное от ChatGPT, пробовал настроить cache-control на стороне apache2 и .htaccess, но ошибка остается. Вообще не меняется. Пробовал и "add" и "put". Вообще много чего испробовал, но ничего так и не сработало. Может быть я что то упустил или делаю не так?
Сервер на ubuntu 18.04 + VestaCP. Ранее таких проблем не наблюдалось. Буду благодарен за любую подсказку.
Спойлеры:
Перепробовал разные сервис воркеры, начиная от pwabuilder.com, заканчивая статьей на хабре https://habr.com/ru/companies/2gis/articles/345552/. Нынешний код SW как раз оттуда
const CACHE = 'cache-update-and-refresh-v1';

// При установке воркера мы должны закешировать часть данных (статику).
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches
            .open(CACHE)
            .then((cache) => cache.addAll([
              '/catalog/view',
              '/catalog/view/theme/default/',
              '/image'
              ]))
    );
});

// При запросе на сервер мы используем данные из кэша и только после идем на сервер.
self.addEventListener('fetch', (event) => {
    // Как и в предыдущем примере, сначала respondWith() потом waitUntil()
    event.respondWith(fromCache(event.request));
    event.waitUntil(
      update(event.request)
      // В конце, после получения "свежих" данных от сервера уведомляем всех клиентов.
      .then(refresh)
    );
});

function fromCache(request) {
    return caches.open(CACHE).then((cache) =>
        cache.match(request).then((matching) =>
            matching || Promise.reject('no-match')
        ));
}

function update(request) {
    return caches.open(CACHE).then((cache) =>
        fetch(request).then((response) =>
            cache.put(request, response.clone()).then(() => response)
        )
    );
}

// Шлём сообщения об обновлении данных всем клиентам.
function refresh(response) {
    return self.clients.matchAll().then((clients) => {
        clients.forEach((client) => {
            // Подробнее про ETag можно прочитать тут
            // https://en.wikipedia.org/wiki/HTTP_ETag
            const message = {
                type: 'refresh',
                url: response.url,
                eTag: response.headers.get('ETag')
            };
            // Уведомляем клиент об обновлении данных.
            client.postMessage(JSON.stringify(message));
        });
    });
}
Код js
// Проверка того, что наш браузер поддерживает Service Worker API.
if ('serviceWorker' in navigator) {
    // Весь код регистрации у нас асинхронный.
    navigator.serviceWorker.register('./pwabuilder-sw.js')
      .then(() => navigator.serviceWorker.ready.then((worker) => {
        worker.sync.register('syncdata');
      }))
      .catch((err) => console.log(err));
}

// Обработчик клика на кнопку приложения
$('.app-button').click(function(){
  var buttonId = $(this).attr('id');
  $('#app-modal-container').removeAttr('class').addClass(buttonId); // убираем все классы и добавляем класс кнопки, чтобы отобразить нужный контент в модальном окне
  $('body').addClass('app-modal-active'); // добавляем класс для блокировки скролла на странице
})

// Обработчик клика на модальное окно
$('#app-modal-container').click(function(){
  $(this).addClass('out'); // добавляем класс для закрытия модального окна с анимацией
  $('body').removeClass('app-modal-active'); // убираем класс для разблокировки скролла на странице
});

  $(window).on('scroll', function() {
  if ('serviceWorker' in navigator)  {
    if ($(this).scrollTop() < 30){ 
      $('.i-app-btn2').fadeOut(1000); // скрываем кнопку при скролле вверх
    }
    if ($(this).scrollTop() >= 34) {
      $('.i-app-btn2').fadeIn(1000); // показываем кнопку при скролле вниз
    }
  } else {
   $('.i-app-btn2').hide(); // скрываем кнопку, если сервисный работник не установлен
    $('.i-app-btn').hide(); 
  }
});

Это в header-е
<link rel="manifest" type="application/manifest+json; charset=utf-8" href="/manifest.webmanifest">

<script src="/my-sw.js" type="text/javascript"></script>

Файл .htaccess
# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.

# 2. In your opencart directory rename htaccess.txt to .htaccess.

# For any support issues please visit: www.opencart.com

Options +FollowSymlinks

# Prevent Directoy listing
Options -Indexes

# Prevent Direct Access to files

Require all denied
## For apache 2.2 and older, replace "Require all denied" with these two lines :
# Order deny,allow
# Deny from all


# SEO URL Settings
RewriteEngine On
# If your opencart installation does not run on the main web folder make sure you folder it does run in ie. / becomes /shop/

RewriteBase /
RewriteCond %{QUERY_STRING} ^(.*)&?page=1$
RewriteRule ^(.*)/?$ /$1?%1%2 [R=301,L] #remove page=1 from url
RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/download/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an "Internal Server Error 500" after enabling any of the following settings, restore the # as this means your host doesn't allow that.

# 1. If your cart only allows you to add one item at a time, it is possible register_globals is on. This may work to disable it:
# php_flag register_globals off

# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off

# 3. Set max upload file size. Most hosts will limit this and not allow it to be overridden but you can try
# php_value upload_max_filesize 999M

# 4. set max post size. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M

# 5. set max time script can take. uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_execution_time 200

# 6. set max time for input to be recieved. Uncomment this line if you have a lot of product options or are getting errors where forms are not saving all fields
# php_value max_input_time 200

# 7. disable open_basedir limitations
# php_admin_value open_basedir none

### Display PHP errors
### Uncomment the commands by removing the # sign in front of it.
# php_flag display_startup_errors on
# php_flag display_errors on
# php_flag html_errors on
# php_flag track_errors on
# php_value error_reporting "E_ALL"

# Cache-Control for static resources

Header set Cache-Control "max-age=604800, public"


# Cache-Control for PWA resources

Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"


# Cache-Control for dynamic content

Header set Cache-Control "no-cache, no-store, must-revalidate"

  • Вопрос задан
  • 159 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы