pwa progressive web App

365 阅读1分钟

1.service worker服务工作线程

11.常驻内存运行 12.代理网络请求 13.依赖HTTPS

navigator.serviceWorker.register('./sw.js',{scope:'/'}).
then(registration=>{
    console.log(registration)
},error=>{console.log(error)})

sw.js

self.addEventListener('install',event=>{
    <!--event.waitUntil(new Promise(resolve=>{-->
    <!--    setTimeout(resolve,5000)//五秒之后去激活-->
    <!--})-->
    event.waitUntil(self.skipWaiting())
})
self.addEventListener('activate',event=>{
     event.waitUntil(self.clients.claim())
     
})
self.addEventListener('fetch',event=>{
    
})

2.promise

readFile(filename,(err,content)=>{
    parseXML(content,(err,xml)=>{
        
    })
})
readFile(filename).then(content=>parseXML(content)).then(xml=>{}).catch(error)
open()then(handle).finally(close)

3.fetch

31.ajax

const xhr=new XMLHttpRequest();
xhr.responseType='json';
xhr.onreadystatechange=()=>{
  if(xhr.readyState===4&&xhr.status==200){
    console.log(xhr.response)
  }
}
xhr.open('GET','./APP.json',true)
xhr.send(null)

fectch


fetch('/app.json',{method:'GET',body:}).then(re=>re.json())
.then(info=>console.log(info)
--------------------------------
const req=newRequest('/app.json',{method:'GET'})
fetch(req).then(re=>re.json()).then(info=>console.log(info)

4.cache API

const CACHE_NAME='cache-v1';
self.addEventListener('install',event=>{
    event.waitUntil(caches.open(CACHE_NAME).then(cache=>{
    cache.addAll([
       '/',
       '/demo.css'
    ])
}))
});

self.addEventListener('activate',event=>{
      //  event.waitUntil(self.clients.claim())下边清除无用缓存
     event.waitUntil(caches.keys().then(cacheNames=>{
       return Promise.all(cacheNames.map(cacheName=>{
         if(cacheName!=CACHE_NAME){
           return caches.delete(cacheName);
         }
       }))
     }))
});
self.addEventListener('fetch',event=>{
    event.respondWith(caches.open(CACHE_NAME).then(cache=>{
        return cache.match(event.request).then(re=>{
            if(re) return re
            return fetch(event.request).then(re=>{
                cache.put(event.request,re.clone())
                return re
            })
        })
    })
    )
});

5.Notification API

Notification.permission
Notification.requestPermission().then(a=>console.log(a))
new Notification('titile",{body:'asasa'})
---------------============
sw.js上下文
Notification.permission--granted
self.registration.showNotification('asda')