Caching Images with Ionic 3

Mariano Alvarez
ninjadevs
Published in
3 min readApr 25, 2017

Ionic is one of the most famous framework around the world to develop hybrid apps using HTML, CSS, Angular. Guess what? We’ll use it to build our app!

One of the challenges that the hybrid apps have nowadays is deal with the offline mode. Yeah this can be translated to more work but at end this will give better experience to the user and improve the app performance. And come on, call an API is kind of boring and too easy :D

Let’s build our app

Start by installing and setting up our environment running these commands:

Install ionic-cli and create a new project:

npm install ionic -g --saveionic start OfflineApp

We are going to use ImgCache.js to cache the images. This beauty will do all the hard work. ImgCache.js is a library made for Cordova taking advantages of the HTML5 file API.

Before jumping into the code, we need to install a few things:

lets configure the plugins in config.xml:

In case you need more information why this is new checkout imgCache.js github.

In order to start working with imgCache.js, We’re going to create a service which be in charge to convert all the library functions into observables.

Most of the code is easy to understand, basically core function were converted into observables by using `bindCallback` function. We declare initNotifier$ variable which will help to notify the observables when the library has been initialized.

But wait, what does normalizeURlWKWview function do? WKWebview does not support file:// neither cdvfile:// protocols, so we need to change the path a little bit in order to point to the right place.

Now We’re ready to use ImgCache.js We are going to create a directive that will cache the images.

Here is a little explanation:

@Input source — image url.
@Output() loaded — will trigger an event when the image has loaded.
ngOnInit() — get image element, bind load and error events and set the src when it’s retrieved
ngOnDestroy() — remove listeners when the directive is destroyed

Run ionic serve to see it working on browser (use Chrome).

Result:

Images are downloaded and saved in the filesystem

Find the complete example here.

https://github.com/mahcr/offline-ionic

BTW — One thing you have to consider is that CORS must be enabled in your server otherwise the imgCache.js can’t download the images. I uploaded the images to imgur for this example. For testing purpose I’m using https://crossorigin.me

Wow Wow, That’s it? Yes!! 🎉 🎉

Want to invite me to a coffee?

--

--

Mariano Alvarez
ninjadevs

Google Developer Expert - Full Stack Developer - Co-Organizer Angular Costa Rica