PWA之所以這么火,還有一個原因是因為它里面含有多項核心技術,比如:Service Worker、Fetch、Caching Files、Web Push Notifications等等。
1、服務工作線程(Service Worker)
服務工作線程是瀏覽器在后臺獨立于網頁運行的腳本,它打開了通向不需要網頁或用戶交互的功能的大門?,F在,它們已包括如推送通知和后臺同步等功能。
簡單代碼示例:
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);