Newer Version Available

This content describes an older version of this product. View Latest

Use Images Uploaded as Asset Files

Asset files are the modern alternative to static resources. Asset files are ideal for images that are used throughout your components and apps—for example, user interface elements like icons—or otherwise aren’t related to a specific record.

Referencing an image stored in an Asset file is straightforward, and fully documented. We present only a simple example here. See Access Content Asset Files the Lightning Web Component Developer Guide for complete details.

The critical elements of an offline-ready implementation are:
  • Access the URL of the asset using the @salesforce/contentAssetUrl module.
  • Provide the image URL via a getter function.
  • Use the getter function for the src attribute of an img tag in your HTML template.

While there are other methods for referencing images in an LWC, the preceding elements are required for offline image access to function. The Komaci static analyzer looks for this specific pattern when determining images to prime. Additionally, your getter function must be statically analyzable. If its result can only be determined at runtime, the image can’t be primed.

Important

Example

1// imageFromAssetFile.js
2import { LightningElement } from 'lwc';
3import ASSET_IMG from '@salesforce/contentAssetUrl/avatars-light-mode';
4import ARCHIVE_IMG from '@salesforce/contentAssetUrl/branding-images';
5
6export default class ImageFromAssetFile extends LightningElement {
7    get assetUrl() {
8        return ASSET_IMG;
9    }
10
11    get assetArchiveUrl() {
12        return ARCHIVE_IMG + '&pathinarchive=images/logo-large.png';
13    }
14}

The assetArchiveUrl function in the preceding example appends a pathinarchive query parameter and value, using a “&” separator. The “&” isn’t used in examples in the standard LWC documentation. The need for the “&” separator is inconsistent between desktop and mobile today, and we consider this discrepancy to be a software defect. For now, adding the “&” separator generally works on both desktop and mobile, even though it results in a double “&&” on desktop.

Warning

With the image URL provided by the getter functions in the preceding component JavaScript, referencing the images in the HTML template is just like referencing any image in HTML. Use it in the src attribute of an HTML img tag.

1<!-- imageFromAssetFile.html -->
2<template>
3    <lightning-card>
4        Display an image directly from an Asset file {assetUrl}
5    </lightning-card>
6
7    <template if:true={assetUrl}>
8        <img src={assetUrl}/>
9    </template>
10
11    <lightning-card>
12        Display an image from an archive Asset file {archUrl}
13    </lightning-card>
14
15    <template if:true={assetArchiveUrl}>
16        <img src={assetArchiveUrl}/>
17    </template>
18
19</template>