Hello Everyone.
In this blog post we will learn the steps to cache files (URL response) in a SAPUI5 application with help of Google Workbox and will be a step closer to being a Progressive Web App.
More can be found about Google Workbox here
https://developers.google.com/web/tools/workbox
.
The various features that can be added to a progressive web application can be found here
https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps
The scope of this post will be limited to use of service worker api in the browser. The files loaded by application is cached in browser during first load. The subsequent requests are intercepted and the files are returned from cache. You can learn more about Service Workers here
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker
.
We will learn
SAPUI5 application structure
You can refer
https://developers.sap.com/tutorials/sapui5-webide-create-project.html
to create a SAPUI5 application. Here, I created a SAPUI5 application with name 'sw-cache'. The structure of a SAPUI5 application looks like below.
(Fig. 1 - Project structure)
The files of our interest is index.html and we will add a new file sw.js at same level with index.html. Service Worker registration happens in index.html and the initialization and configurations are added in sw.js.
Registering a Service Worker
Initialize Service Worker in index.html by adding the script below.
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js')
.then(function(registration) {
console.log('[success] scope: ', registration.scope);
}, function(err) {
console.log('[fail]: ', err);
});
}
</script>
In sw.js file, we define the route patterns to be cached, the details are commented alongside code. We can use multiple caches based on file types or routes, or just one cache. The regex route pattern input to map a cache can be tailored based on the design.
importScripts
Pedro Pascal
Se unió el 07/03/2018