How to Make Your Web Apps Work Offline?

Want create site? Find Free WordPress Themes and plugins.

Our life revolves around the internet! We run away from all things bad signal, power failures, router issues, etc. etc!

But no matter how hard we try to escape, it’s still a harsh reality, that we have to deal with, on a daily basis. And guess what? We are relying more and more on web apps that are increasingly replacing the traditional desktop applications (which, by the way, work offline).

The need for web apps to work ‘offline’ is important. Period.

There are a couple of ways to go about it. In this blog, we’ll focus on one method where you can make your web apps work offline using cache1 with the help of service worker.

Let’s get started

Step I. Service Worker2 Creation

Create a js file named service-worker.js in your project.

Step II. Service Work Registration

Add the following code in the js file which is loaded by default for e.g. main.js / app.js

 

if ('serviceWorker' in navigator) {
 
navigator.serviceWorker
 
.register('./service-worker.js')
.then(function() { console.log('Service Worker Registered'); });

Step III. Creating Cache

Add the following the code to service-worker.js file created in Step 1:

 

var CACHE_VERSION = 'app-v1';
var CACHE_FILES = [
 
'js/jquery-1.11.3.min.js',
'js/bootstrap.min.js',
'js/jquery.easing.min.js',
'js/custom.js',
'css/bootstrap.min.css',
'css/custom.css',
'http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800',
'https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js'
 
];
 
// Listen to installation event
 
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(function (cache) {
console.log('Opened cache');
return cache.addAll(CACHE_FILES);
 
})
);
});

A brief explanation of the code written above.

  • An install event listener was added to the service worker (hence this), followed by adding ExtendableEvent.waitUntil() method onto that event. This makes sure that service worker will not be installed until waitUntil() has not been invoked.
  • caches.open() is used to create a new version of cache. This will return a promise for the cache that has been created once you get the response addAll() method is invoked on the created cache.
  • The installation fails when the promise is rejected and the worker will not perform any activity.
  • The service worker activities on the success of the install event.

Step IV. Update Cache – Activation Event

In the same file `service-worker.js` add the following lines below the existing code:

 

// Listen to activation event
self.addEventListener('activate', function (event) {
  event.waitUntil(
 
 caches.keys().then(function(keys){
return Promise.all(keys.map(function(key, i){
if(key !== CACHE_VERSION){
 
return caches.delete(keys[i]);
}
}))
})
 
)
});

A brief explanation of the code written above.

  • Activation event is used to activate events that were broken in the previous version, e.g. updating your old cache. This is also useful for clearing up unnecessary data consuming the disk space.
  • Generally each browser has a specific amount of cache storage that is been allocated to service worker, hence the need to clear disk space frequently.
  • waitUntil() is used to block all your other events until the success of previous event. This assures, your clean up operation is successful before your first fetch event occurs.

Step V. Serve App Shell3 Offline From Cache

In the same file service-worker.js add the following lines below the existing code:

 

self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request).then(function(res){
if(res){
return res;
}
requestBackend(event);
})
)
});
function requestBackend(event){
var url = event.request.clone();
return fetch(url).then(function(res){
//if not a valid response send the error
if(!res || res.status !== 200 || res.type !== 'basic'){
return res;
}
var response = res.clone();
caches.open(CACHE_VERSION).then(function(cache){
cache.put(event.request, response);
});
return res;
})
}

A brief explanation of the code written above.

In the above, a fetch request is invoked to get cache resources of our web app. You can also attach your fetch event listener to the service worker and then responsdWith() method can be invoked on the required event.

Please Note: Chrome has an option of service worker if you click on inspect element application tab. Here you can see all your cache storage. There is also a provision to test your app offline, by clicking on the offline checkbox available on the top.

While working with Firefox, enable service worker over HTTP option in the Firefox Developer Tools Settings.

We’re Done! Your app now has offline support!

Did you find apk for android? You can find new Free Android Games and apps.

Tags

Related Posts

Leave A Comment