To make an Angular application work offline, you need to implement a Progressive Web App (PWA), which leverages service workers to cache assets and enable offline capabilities. Here’s a step-by-step guide to achieve that:
First, you need to add the Angular PWA package to your project. This package configures the necessary settings for service workers and caching.
Run the following command in your Angular project directory:
ng add @angular/pwa
This command will:
The `ngsw-config.json` file determines how your service worker behaves, including which files are cached and how they are managed.
By default, this file will cache the following:
-> All assets under the `src/assets` directory.
-> The index page (`index.html`).
For 100% offline capability, caching dynamic data from APIs is critical. Use the service worker to cache API responses and serve them when offline.
You can modify the `ngsw-config.json` file to add specific assets or configure advanced caching strategies.
For example:
{ "index": "/index.html", "assetGroups": [ { "name": "app", "installMode": "prefetch", "resources": { "files": [ "/favicon.ico", "/index.html", "/*.css", "/*.js", "/manifest.webmanifest" ] } }, { "name": "assets", "installMode": "prefetch", "updateMode": "prefetch", "resources": { "files": [ "/assets/**", "/*.svg", "/*.png", "/*.jpg", "/*.jpeg", "/*.woff2" ] } }, { "dataGroups": [ { "name": "api-cache", "urls": [ "https://api.example.com/**" ], "cacheConfig": { "strategy": "freshness", "maxSize": 100, "maxAge": "6h", "timeout": "10s" } } ] } ] }
Typically through the `ServiceWorkerModule` provided by Angular’s PWA package. It’s used to configure the service worker in your Angular application.
`ngsw-worker.js`: This refers to the service worker script that Angular’s build process generates when you add the `@angular/pwa package`. It’s responsible for managing the caching of assets and API responses.
In `app.module.ts` file,
providers: [ ..., ..., ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production, // Flag ensures that the service worker is only active in production mode registrationStrategy: 'registerWhenStable:30000', // Wait 30 seconds after app is stable }) ]
For Standalone APIs:
In `app.config.ts` file,
providers: [ ..., ..., provideServiceWorker('ngsw-worker.js', { enabled: environment.production, // Flag ensures that the service worker is only active in production mode registrationStrategy: 'registerWhenStable:30000', // Wait 30 seconds after app is stable }), ]
Once all steps are implemented, build your app for production:
ng build --prod
Then, serve it using a simple server to ensure offline functionality works as expected:
http-server -p 8080
For AngularJS (v1.x):
Since AngularJS (the 1.x version) is older, it doesn’t have built-in support for service workers like Angular (2+). However, you can still make your AngularJS app work offline By Following ways.
-> Setting up service workers manually
-> Using html5 cache manifest and `$templateCache`
Since AngularJS doesn’t have out-of-the-box support for PWAs, you need to implement service workers manually.
The service worker handles the caching of your application’s assets (HTML, CSS, JS, images) and dynamic data. In the root of your AngularJS app, create a file called `service-worker.js`.
Here’s a basic service worker script:
// Cache name const CACHE_NAME = 'angularjs-app-cache-v1'; // Assets to cache const ASSETS_TO_CACHE = [ '/', '/index.html', '/css/styles.css', '/js/app.js', '/images/logo.png', // Add more assets like HTML, JS, CSS files ]; // Install Service Worker and Cache Files self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(ASSETS_TO_CACHE); }) ); }); // Activate Service Worker and Clean Old Caches self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((cacheNames) => { return Promise.all( cacheNames .filter((cacheName) => cacheName !== CACHE_NAME) .map((cacheName) => caches.delete(cacheName)) ); }) ); }); // Fetch Resources from Cache or Network self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cachedResponse) => { if (cachedResponse) { return cachedResponse; // Return cached resource } return fetch(event.request).then((response) => { return caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, response.clone()); // Cache new resource return response; }); }); }) ); });
This service worker script:
In your AngularJS app’s `index.html`, register the service worker:
This code checks if the browser supports service workers and registers it if available.
-> Build your app: Ensure all assets are available in the ASSETS_TO_CACHE list.
-> Test the offline behavior: Use the Network tab in the browser’s Developer Tools to simulate offline mode.
To make your application work offline, you have to cache every file with the html5 cache manifest. Even the .html files, images, css, everything…
An example manifest:
CACHE MANIFEST /angular.js /index.html /page/home.html /page/profile.html NETWORK: * ``` How to include and use cache manifest check: https://web.dev/articles/appcache-beginner
For debugging:
Clearing a app cache under chrome enter url “`chrome://appcache-internals/`”
Instead of placing the html code in many own html files, you can include them in `index.html` like this:
Then your templateURL is “`one.html`” without a subpath.
Check docs:
https://docs.angularjs.org/api/ng/directive/script
https://docs.angularjs.org/api/ng/service/$templateCache
Hint:
You don’t need to place any paths there. During the rendering phase, AngularJS will store every html file in the `$templateCache` under its id placed in those script elements.
Note:
While `$templateCache` provides some basic caching for AngularJS apps, their usage is limited to the current session and doesn’t persist between page reloads or browser restarts. If you need more comprehensive offline support, you should consider implementing **service workers** for persistent caching and full offline capabilities. However, for short-term session caching and performance optimization, `$templateCache` are useful tools
By following these steps, your Angular application will work offline, caching both static and dynamic assets.
Additionally you can cache the API Response, by Implementing Angular Interceptor (for angular 2+). Also you can use the localStorage or IndexDB to provide more accessibility in offline mode.