首页 > 解决方案 > 更改 app.js 文件后,服​​务人员停止工作

问题描述

我的 PWA 一直运行良好,直到今天早上。在编程期间,我更改了一些内容,使服务人员停止工作。

它仍在注册中,但在我的计算机与网络断开连接后,服务人员不再显示脱机后备。

我找不到问题。不知道,出了什么问题。

代码不多,但我不知道如何分解它。我不认为问题出在 service-worker 文件中。

这是我的sw.js

const staticAssets = [
    './',
    './menu.html',
    './jquery.min.js',
    './styles.css',
    './app.js',
    './images',
    './fallback.json',
    './images/system/offline.png',
    'sw.js'    
];




self.addEventListener('install', async event => {
    const cache = await caches.open('static-assets');
    cache.addAll(staticAssets);
});

self.addEventListener('fetch', event => {
    const req = event.request;
    const url = new URL(req.url);

    if(url.origin === location.origin){
        event.respondWith(cacheFirst(req));
    }else{
        event.respondWith(networkFirst(req));
    }

});


async function cacheFirst(req){
    const cachedResponse = await caches.match(req);
    return cachedResponse || fetch(req);
}

async function networkFirst(req){
    const cache = await caches.open('dynamic-content');
    try{
        const res = await fetch(req);
        cache.put(req, res.clone());
        return res;
    }catch(err){
        const cachedResponse = await cache.match(req);
        return cachedResponse || caches.match('./fallback.json');
    }
}

如果你真的想帮忙,你可能想看看这里的实际项目。检查app.js文件,我想问题的可能性很高。通过在断开前后单击菜单按钮可以看到 sw 不工作。

https://jaxpot.000webhostapp.com

app.js文件:

const apiKey = 'XYZ'
const topbar = document.querySelector('#topbar');
const highbar = document.querySelector('.stat-back.high');
const lowbar = document.querySelector('.stat-back.low');
const content = document.querySelector('#content');
const menuBtn = document.querySelector('#menu-btn');

var sourceSelector = document.querySelector('#sourceSelector');
var defaultSource = 'the-washington-post';

window.addEventListener('load', async  e => {
    //adjust topbar to mobile device
    if(typeof window.orientation != 'undefined'){
        fitScreen('orientation', window.orientation);
        window.addEventListener('orientationchange', function() {
            fitScreen('orientation', window.orientation)
        });
        window.addEventListener('scroll', function() {
            fitScreen('scroll', window.orientation)
        });
    }else if(typeof screen.orientation != 'undefined'){
        fitScreen(screen.orientation);
        window.addEventListener('orientationchange', function() {
            fitScreen('orientation', screen.orientation)
        });
        window.addEventListener('scroll', function() {
            fitScreen('scroll', screen.orientation)
        });
    }else{
        topbar.style.top="0px";
    }

    menuBtn.addEventListener('change', e => {
        toggleMenu(e.target);
    });



    updateNews();
    await updateSources();
    sourceSelector.value = defaultSource;

    sourceSelector.addEventListener('change', e => {
        updateNews(e.target.value);
    });


    if('serviceWorker' in navigator){
        try{
            navigator.serviceWorker.register('sw.js');
            console.log(`SW registration complete`);
        }catch(err){
            console.log(`SW registration failed`);
        }
    }else{
        console.log(`SW not supported`);
    }
});




async function fitScreen(origin, deviceOrientation){
    if (Math.abs(deviceOrientation) === 90) {
        // Landscape
        highbar.style.backgroundColor="#eeeeee";
        if(window.innerWidth > 700){
            lowbar.style.backgroundColor="#eeeeee";
            lowbar.style.opacity = "0";
            lowbar.style.pointerEvents = "none";
        }else{
            lowbar.style.backgroundColor="#fff";
            lowbar.style.opacity = "0";
            lowbar.style.pointerEvents = "none";
        }
        topbar.style.cssText = "";      
    }else{
        // Portrait

        if(origin == 'orientation'){



            setTimeout(function(){

                var scrH = screen.height;
                var srcAH = screen.availHeight;
                var winH = window.innerHeight;

                if(srcAH > winH){
                    if(srcAH-winH > 20){
                        console.log("iOS - browser");
                        highbar.style.display="block";
                        lowbar.style.display="none";
                    }else{
                        console.log("new iOS - full");
                        highbar.style.display="none";
                        lowbar.style.display="block";
                        if(window.innerWidth > 700){
                            lowbar.style.backgroundColor="#eeeeee";
                            lowbar.style.opacity = "0";
                            lowbar.style.pointerEvents = "none";
                        }else{
                            lowbar.style.backgroundColor="#fff";
                            lowbar.style.opacity = "0";
                            lowbar.style.pointerEvents = "none";
                        }
                    }

                    topbar.style.cssText = "top:0px; padding-top:11px";
                }else if(winH > srcAH ){
                    console.log("old iOS - full");

                    topbar.style.cssText = "top:0px; padding-top:31px; height:80px";
                    highbar.style.display="none";
                    lowbar.style.display="none";
                }

            },100);
        }else if(origin == 'scroll'){
            if(document.querySelector('body').scrollTop > 19){
                lowbar.style.backgroundColor="#2a3443";
                lowbar.style.opacity = "1";
                lowbar.style.pointerEvents = "";
            }else{
                if(window.innerWidth > 700){
                    lowbar.style.backgroundColor="#eeeeee";
                    lowbar.style.opacity = "0";
                    lowbar.style.pointerEvents = "none";
                }else{
                    lowbar.style.backgroundColor="#fff";
                    lowbar.style.opacity = "0";
                    lowbar.style.pointerEvents = "none";
                }
            }
        }

    }  
}




async function updateNews(source = defaultSource){
    const res = await fetch(`https://newsapi.org/v1/articles?source=${source}&apiKey=${apiKey}`);
    const json = await res.json();

    content.innerHTML = json.articles.map(createArticle).join('\n');
}
async function updateSources(){
    const res = await fetch(`https://newsapi.org/v1/sources`);
    const json = await res.json();

    sourceSelector.innerHTML = json.sources
    .map(src => `<option value="${src.id}">${src.name}</option>`)
    .join('\n')
}


function createArticle(article){
    return `
        <div class="article">
            <a href = "${article.url}">
                <h2>${article.title}</h2>
                <img src="${article.urlToImage}">
                <p>${article.description}</p>
            </a>
        </div>
        <div class="devider"></div>
    `
}



async function toggleMenu(el){
      if(el.checked == true){

        var res = await fetch(`menu.html`);
        var menu = await res.text();

        content.innerHTML = menu;

        var freeSpace = window.innerHeight - (parseInt(window.getComputedStyle(topbar, null).getPropertyValue("height").split("px")[0]) + parseInt(window.getComputedStyle(content, null).getPropertyValue("height").split("px")[0]) + parseInt(window.getComputedStyle(document.querySelector("footer"), null).getPropertyValue("height").split("px")[0]));
        document.querySelector('.whitespace').style.height = Math.max(freeSpace, 0) + "px";


      }else{
          updateNews(defaultSource);
      }
  }

标签: service-worker

解决方案


推荐阅读