Progressive Web Apps(PWA)核心技术

PWA之所以这么火,还有一个原因是因为它里面含有多项核心技术,比如:Service Worker、Fetch、Caching Files、Web Push Notifications等等。

1、服务工作线程(Service Worker)

服务工作线程是浏览器在后台独立于网页运行的脚本,它打开了通向不需要网页或用户交互的功能的大门。现在,它们已包括如推送通知和后台同步等功能。
简单代码示例:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

2、网络请求(Fetch
fetch()允许您发出类似于XMLHttpRequest(XHR)的网络请求。 主要区别在于Fetch API使用Promises,它使用一个更简单和更清洁的API,避免了回调和不得不记住XMLHttpRequest的复杂API的苦境。
简单代码示例:

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

3.缓存文件(Caching Files
Service Worker API带有一个Cache接口,可以让您创建按请求键入的响应存储。 虽然这个接口是面向服务人员的,但它实际上暴露在窗口中,并且可以从脚本中的任何地方访问。 入口点是缓存。
简单代码示例:

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open(cacheName).then(function(cache) {
      return cache.addAll(
        [
          '/css/bootstrap.css',
          '/css/main.css',
          '/js/bootstrap.min.js',
          '/js/jquery.min.js',
          '/offline.html'
        ]
      );
    })
  );
});

4、推送信息(Web Push Notifications
推送是基于Service Worker,因为Service Worker在后台操作。它允许服务器向用户提示一些信息,并根据用户不同的行为进行一些简单的处理。
简单代码示例:

let options = {
  "body": "Did you make a $1,000,000 purchase at Dr. Evil...",
  "icon": "images/ccard.png",
  "vibrate": [200, 100, 200, 100, 200, 100, 400],
  "tag": "request",
  "actions": [
    { "action": "yes", "title": "Yes", "icon": "images/yes.png" },
    { "action": "no", "title": "No", "icon": "images/no.png" }
  ]
}
serviceWorkerRegistration.showNotification(title, options);

你可能感兴趣的:(Progressive Web Apps(PWA)核心技术)