我的浏览器注册服务工作者并缓存网址,但它不能脱机工作?

时间:2016-08-08 02:56:25

标签: caching service-worker

这在网上注册并完美无缺。但是,当服务器关闭时,以及刷新页面时,注册的服务工作者不再显示在控制台中,缓存存储中也没有缓存。

import org.apache.spark.ml.clustering.LDA 
import org.apache.spark.sql.{Row, SQLContext} 
import org.apache.spark.sql.types.{StructField, StructType}

val lda = new LDA()   .setK(10)   .setMaxIter(10)   .setFeaturesCol("features")

val model = lda.fit(countVectors)

val transformed = model.transform(countVectors)

在sw.js

if ("serviceWorker" in navigator){
navigator.serviceWorker.register("/sw.js").then(function(registration){
    console.log("service worker reg", registration.scope)
}).catch(function(error){
        console.log("Error:", error);
    })
}

1 个答案:

答案 0 :(得分:0)

您正在将文件正确添加到缓存中,但是您错过了根据请求返回缓存文件。

您的sw.js也应该有以下代码:

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

        return fetch(event.request);
      }
    )
  );
});

来自Introduction to service workers

Morover,你宁愿缓存/而不是/index.html通常,你不直接点击index.html文件。

您的服务工作人员在离线时不会显示任何console.log,因为您没有任何activate代码。 This article - offline cookbook对了解细节非常有用。