NativeScript Core

Image Cache

The image-cache module contains the Cache class, which handles image download requests and caches the already downloaded images.

Basics

Using Cache objects requires the tns-core-modules/ui/image-cache module.

const Cache = require("tns-core-modules/ui/image-cache").Cache;
import { Cache } from "tns-core-modules/ui/image-cache";

Requesting and caching images with image-cache module while using a placeholder image.

const cache = new Cache();
cache.placeholder = fromFile("~/images/logo.png");
cache.maxRequests = 5;

// set the placeholder while the desired image is downloaded
viewModel.set("imageSource", cache.placeholder);

// Enable download while not scrolling
cache.enableDownload();

let cachedImageSource;
const url = "https://avatars1.githubusercontent.com/u/7392261?v=4";
// Try to read the image from the cache
const image = cache.get(url);

if (image) {
    // If present -- use it.
    cachedImageSource = imageSource.fromNativeSource(image);
    viewModel.set("imageSource", cachedImageSource);
} else {
    // If not present -- request its download + put it in the cache.
    cache.push({
        key: url,
        url: url,
        completed: (image, key) => {
            if (url === key) {
                cachedImageSource = fromNativeSource(image);
                viewModel.set("imageSource", cachedImageSource); // set the downloaded image
            }
        }
    });
}

// Disable download while scrolling
cache.disableDownload();
const cache = new Cache();
cache.placeholder = fromFile("~/images/logo.png");
cache.maxRequests = 5;

// set the placeholder while the desired image is donwloaded
viewModel.set("imageSource", cache.placeholder);

// Enable download while not scrolling
cache.enableDownload();

let cachedImageSource;
const url = "https://avatars1.githubusercontent.com/u/7392261?v=4";
// Try to read the image from the cache
const myImage = cache.get(url);

if (myImage) {
    // If present -- use it.
    cachedImageSource = fromNativeSource(myImage);
    viewModel.set("imageSource", cachedImageSource);
} else {
    // If not present -- request its download + put it in the cache.
    cache.push({
        key: url,
        url: url,
        completed: (image, key) => {
            if (url === key) {
                cachedImageSource = fromNativeSource(image);
                viewModel.set("imageSource", cachedImageSource); // set the downloaded iamge
            }
        }
    });
}

// Disable download while scrolling
cache.disableDownload();
<Image src="{{ imageSource }}" stretch="aspectFill" />

Improve this document

Demo Source


API Reference for

See Also Android Image Optimization