vkuzel.com

Creating offline fallback page for the AngularJs web application using ApplicationCache

2015-08-27

I needed to create a page that is going to be displayed to user who opened my application in the past but currently is without internet connection or he is working with the application but his connection is suddenly lost.

Client is opening the application but does not have connection available

For this purpose I decided to use ApplicationCache. I wanted that user will be redirected to offline.html page if index.html page is not loaded because connection is lost. This means I couldn’t put manifest directive to index.html page because page with manifest is automatically cached but I needed only offline.html page to be cached. So I placed manifest to offline.html instead and invoked it by placing object element to index.html.

<object type="text/html" data="/offline.html" style="widht: 1px; height: 1px;”></object>

Then defined failover page in ApplicationCache manifest file.

CACHE MANIFEST
# Version 1

NETWORK:
*

FALLBACK:
//offline.html

From now if user tries to open the application without internet connection or without server working a offline.html page will be displayed to him instead.

Client is working with the application and connection is suddenly lost

At this state only requests to server are done via XHR so we just need to intercept responses and if error occurs because connection is lost to redirect client to offline page. Interceptor can be added by $httpProvider.

$httpProvider.interceptors.push(function() {
    return {
        'responseError': function(rejection) {
            if (rejection.status == 0) {
                location.reload(true);
            }
        }
    };
});