在GitHub页面上显示服务工作者注册失败,在localhost页面显示成功

时间:2018-10-09 08:58:49

标签: javascript es6-promise service-worker angular-service-worker

我在本地服务器localhost:8000中运行我的项目。服务人员成功工作。但是,当我在Github中运行同一项目时,它表明服务工作者注册失败。下面附上我的错误快照。

我的Gitgub页面链接:https://nayaksofia.github.io/RestaurantReviewTest1/

我的Github项目链接:https://github.com/nayaksofia/RestaurantReviewTest1

您能帮助我解决此问题吗?

main.js

if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
  // Registration was successful
  console.log('ServiceWorker registration successful with scope: ', 
registration.scope);
 }, function(err) {
  // registration failed :(
  console.log('ServiceWorker registration failed: ', err);
  });
 });
} 

sw.js

  //Install a service worker

var CACHE_NAME = 'my-restuarant-cache-v1';
var urlsToCache = [
 '/img/1.jpg',
'/img/2.jpg',
'/img/3.jpg',
'/img/4.jpg',
'/img/5.jpg',
'/img/6.jpg',
'/img/7.jpg',
'/img/8.jpg',
'/img/9.jpg',
'/img/10.jpg',
'/',
'/index.html',
'/restaurant.html',
'/css/styles.css',
'/js/dbhelper.js',
'/js/main.js',
'/js/restaurant_info.js',
'/data/restaurants.json'

];

 self.addEventListener('install', function(event) {
 // Perform install steps
event.waitUntil(
  caches.open(CACHE_NAME)
  .then(function(cache) {
    console.log('Opened cache');
    return cache.addAll(urlsToCache);
   })
  );
});

 //Activate 
 self.addEventListener('activate', function(event) {

 var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];
 console.log("Service worker activated");

 event.waitUntil(
  caches.keys().then(function(cacheNames) {
    return Promise.all(
     cacheNames.map(function(cacheName) {
      if (cacheWhitelist.indexOf(cacheName) === -1) {
        return caches.delete(cacheName);
        }
       })
     );
   })
  );
});

 //Cache and Return Request 

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
      // Cache hit - return response
      if (response) {
        return response;
      }
      var fetchRequest = event.request.clone();

      return fetch(fetchRequest).then(
        function(response) {
          // Check if we received a valid response
           if(!response || response.status !== 200 || response.type !== 
  'basic') {
            return response;
          }

          var responseToCache = response.clone();

          caches.open(CACHE_NAME)
            .then(function(cache) {
              cache.put(event.request, responseToCache);
            });

          return response;
          }
        );
      })
     );
  });

img-1:ServiceWorkerFailed-MyProjectGitHubPage

img-2:ServiceWorkerWorked-MyProjectLocalHost

谢谢。

0 个答案:

没有答案