firebase-cms icon indicating copy to clipboard operation
firebase-cms copied to clipboard

Service worker code caching

Open MattiJarvinen opened this issue 8 years ago • 0 comments

angular/service-worker is a good option to cache files for returning users. angular.io source code provides nice way to update service worker on navigation event.

Something along the lines of https://github.com/angular/angular/blob/master/aio/src/app/sw-updates/sw-updates.service.ts and RefresherService

import { SwUpdatesService } from '../modules/sw-updates/sw-updates.service';
import { Injectable, OnDestroy } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { LoggerService } from './logger.service';
import { Subject } from 'rxjs/Rx';

@Injectable()
export class RefresherService implements OnDestroy {
    private swUpdateActivated = false;
    private unsubscribe: Subject<void> = new Subject();

    constructor( router: Router, swUpdatesService: SwUpdatesService, private logger: LoggerService) {
        swUpdatesService.updateActivated
        .takeUntil(this.unsubscribe)
        .subscribe( () => this.swUpdateActivated = true);

        router.events
        .takeUntil(this.unsubscribe)
        .filter( event => event instanceof NavigationStart )
        .subscribe( (event: NavigationStart) => {
            if (this.swUpdateActivated) {
                this.log(`Update during navigation ${event.url}`);
                window.location.assign( event.url );
            } else {
                this.log(`No need to update on navigation: ${event.url}`);
            }
        })
    }

    private log( message: string): void {
        this.logger.log('Service Worker Refresher', message);
    }

    public ngOnDestroy() {
        this.unsubscribe.next();
        this.unsubscribe.complete();
    }
}

MattiJarvinen avatar Sep 22 '17 06:09 MattiJarvinen