UI Engineer продуктов из будущего
в ForgeRock
Google Experts это глобальная сеть опытных разработчиков, дизайнеров, маркетологов, активно поддерживающих разработчиков, стартапы и компании, которые изменяют мир своими веб- и мобильными приложениями
Progressive Web App (PWA) is a term used to denote a new software development methodology.
Unlike traditional applications, Progressive Web App can be seen as an evolving hybrid of regular web pages (or websites) and a mobile application.
Синхронизация данных в фоновом режиме
Централизованное получение обновлений результатов сложных вычислений (геолокация, данные с гироскопа и т.д.) для использования сразу несколькими частями приложения
Компиляция и управление зависимостями CoffeeScript, less, CJS/AMD и т.д. на стороне клиента
Повышениe быстродействия за счет предзагрузки ресурсов, которые могут потребоваться в ближайшем будущем, например, следующего фото при просмотре фотоальбома
Программируемый сетевой прокси-сервер, расположенный между приложением, запущенным в браузере и сетью
Браузер
Отдельный контекст для выполнения фоновых задач, который не блокирует UI
// app.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(function(registration) {
// Successful registration
console.log("Service Worker Registered", registration);
})
.catch(function(err) {
// Registration failed
console.log("Service Worker Failed to Register", err);
})
}
// sw.js
var currentCacheName = 'pwaday-sw-v1';
var filesToCache = [
'/index.html',
'/css/main.css',
'/img/logo.png',
'/js/main.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(currentCacheName).then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
// sw.js
self.addEventListener('activate', function(event) {
event.waitUntil(
// Get all the cache names
caches.keys().then(function(cacheNames) {
return Promise.all(
// Get all the items that are not the current one
cacheNames.filter(function(cacheName) {
return cacheName != currentCacheName;
}).map(function(cacheName) {
// Delete the items
return caches.delete(cacheName);
})
); // end Promise.all()
}) // end caches.keys()
); // end event.waitUntil()
});
// sw.js
self.addEventListener('fetch', function(event) {
// Do stuff with fetch events
});
self.addEventListener('message', function(event) {
// Do stuff with postMessage() received from document
});
self.addEventListener('push', function(event) {
// Do stuff with push-notifications received from server
});
Обновляется .js-файл Service Worker
Регистрируется новый SW и вызывается событие install
Старый SW все еще управляет страницами приложения, поэтому новый находится в состоянии installed / waiting
Когда все страницы (закладки) приложения закрываются, старый SW переходит в состояние redundant, контроль переходит к новому
Вызывается событие activate
self.addEventListener('install', (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
// sw.js
self.addEventListener('fetch', function(event) {
event.respondWith(
...
);
});
// sw.js
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
);
});
Вернем то, что находится в cache
// 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);
}
)
);
});
Вернем то, что находится в cache. В случае неуспеха - возьмем из сети.
// sw.js
var currentCacheName = 'pwaday-sw-v1';
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(resp) {
return resp || fetch(event.request).then(function(response) {
return caches.open(currentCacheName).then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Вернем то, что находится в cache. В случае неуспеха - возьмем из сети и поместим в cache (на будущее)
// sw.js
var currentCacheName = 'pwaday-sw-v1';
this.addEventListener('fetch', function(event) {
event.respondWith(
fetch(e.request)
.then((response) => {
return caches.open(currentCacheName).then((cache) => {
cache.put(e.request.url, response.clone());
return response.clone();
});
})
);
});
toolbox.precache(filesToCache);
toolbox.networkFirst, toolbox.cacheFirst, toolbox.fastest,
toolbox.cacheOnly, toolbox.networkOnly
toolbox.router.get('/assets/data/(.*)', toolbox.networkFirst, {
cache: { name: currentCacheName }
});