Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

问题: 如何统计上报缓存命中率 #23

Open
robbiemie opened this issue May 6, 2019 · 1 comment
Open

问题: 如何统计上报缓存命中率 #23

robbiemie opened this issue May 6, 2019 · 1 comment

Comments

@robbiemie
Copy link

问题描述:

如题。

我目前采用 postMessage 方式,将命中信息传递给主进程,在主进程进行上报统计。不过,有个问题是在主进程,并有时并未监听接收到消息

下面是我的缓存命中统计的埋点,下面代码所注

sw-register.js

  navigator.serviceWorker.addEventListener('message', function (e) {
    console.log('postMessage数据', e.data)

    if (e.data.type === 'update') {
      console.log('重新加载页面', e.data)
      location.reload()
    }
    if (e.data.type === 'cache') {
      console.log('命中缓存', e.data)
    }
    if (e.data.type === 'uncache') {
      console.log('缓存未命中', e.data)
    }
  })

sw.js

self.addEventListener('fetch', function (evt) {
 // ...
  evt.respondWith(
    caches.match(evt.request).then(async function (response) {
      if (response) {
          clients.forEach(client => {
              ///////////////////////->命中缓存<-////////////////////////////
              // client.postMessage({ type: 'cache', msg: requestStr })
          })
        return response
      }
      return fetch(evt.request).then(function (response) {
        let cpResponse = response.clone()
        // console.log('fetch获取到的response:', response)
        caches.open(version).then(function (cache) {
            cache.put(evt.request, cpResponse)
            clients.forEach(client => {
              ///////////////////////->未命中缓存<-//////////////////////////
              client.postMessage({ type: 'uncache', msg: requestStr })
            })
          })
        return response
      })
    }).catch(function (err) {
      console.error('fetch 接口错误', err)
      throw err
    })
  )
})

请问:
1.为何使用 postMessage 方式,无法监听接收到消息?
2.ServiceWorker缓存成功后,有没有更好的方法进行上报量化统计?

@robbiemie
Copy link
Author

robbiemie commented May 6, 2019

完整代码: code link 感谢。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant