簡體   English   中英

成功安裝Service Worker后更新UI

[英]Update UI when Service Worker installed successfully

看起來Service Worker在工作程序上下文中運行,並且無法訪問DOM。 但是,一旦安裝了Service Worker,我希望我的用戶知道該應用程序現在可以脫機工作。 我怎樣才能做到這一點?

當Service Worker處於activated state ,這是顯示吐司“ Content is cached for offline use ”的理想時機。 注冊服務工作者時,請嘗試使用以下代碼。

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/service-worker.js').then(function(reg) {
    // updatefound is fired if service-worker.js changes.
    reg.onupdatefound = function() {
      var installingWorker = reg.installing;

      installingWorker.onstatechange = function() {
        switch (installingWorker.state) {
          case 'installed':
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and the fresh content will
              // have been added to the cache.
              // It's the perfect time to display a "New content is available; please refresh."
              // message in the page's interface.
              console.log('New or updated content is available.');
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a "Content is cached for offline use." message.
              console.log('Content is now available offline!');
            }
            break;

          case 'redundant':
            console.error('The installing service worker became redundant.');
            break;
        }
      };
    };
  }).catch(function(e) {
    console.error('Error during service worker registration:', e);
  });
}

在測試完@Prototype Chain答案之后 ,我想使用named functions (而不是嵌套的anonymous functions作為事件處理程序,以使代碼看起來更令人愉悅,並希望以后更容易理解。

但是僅在花了一些時間對文檔進行排序之后,我才設法在正確的對象上偵聽了正確的事件。 因此,在這里分享我的工作示例,以希望使其他人免於繁瑣的過程。

    // make sure that Service Workers are supported.
    if (navigator.serviceWorker) {
        navigator.serviceWorker.register('/sw.js')
            .then(function (registration) {
                console.log("ServiceWorker registered");

                // updatefound event is fired if sw.js changed
                registration.onupdatefound = swUpdated;
            }).catch(function (e) {
            console.log("Failed to register ServiceWorker", e);
        })
    }

    function swUpdated(e) {
        console.log('swUpdated');
        // get the SW which being installed
        var sw = e.target.installing;
        // listen for installation stage changes
        sw.onstatechange = swInstallationStateChanged;
    }

    function swInstallationStateChanged(e) {
        // get the SW which being installed
        var sw = e.target;
        console.log('swInstallationStateChanged: ' + sw.state);

        if (sw.state == 'installed') {
            // is any sw already installed? This function will run 'before' 'SW's activate' handler, so we are checking for any previous sw, not this one.
            if (navigator.serviceWorker.controller) {
                console.log('Content has updated!');
            } else {
                console.log('Content is now available offline!');
            }
        }

        if (sw.state == 'activated') {
            // new|updated SW is now activated.
            console.log('SW is activated!');
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM