7

I am trying to dynamically load an image from a static resource within LWC. When the user loads the page, a query parameter is provided called locationCode. Depending on the locationCode, a different static resource will be used. The static resources have a format similar to Resource_Images_XX, where XX is the locationCode. I should note this is implemented within communities.

Since I won't know the locationCode until after the page has loaded, I cannot do the following:

import imageResource from '@salesforce/resourceUrl/Resource_Images_XX';

Is there an alternative way to load static resource images when I cannot use the import statement?

Would any of these URL paths work within my JavaScript file?

  • url('sfsites/c/resource/Resource_Images_CA/images/${this._backgroundImage}')
  • url('sfsites/c/file-asset/${this._backgroundImage}')

3 Answers 3

12

You would normally upload a ZIP file, and use it in the manner described in the docs:

import TRAILHEAD_CHARACTERS from '@salesforce/resourceUrl/trailhead_characters';

// ...

einsteinUrl = TRAILHEAD_CHARACTERS + '/images/einstein.png';

Loading a dynamic resource name directly is not supported; this is because the compiler will verify the resource name before successfully compiling, reducing the odds of typos or accidental removal of used resources.

3
  • @sfdxfox if that static resource name misspelled then how can we check that error here? Commented May 30, 2020 at 15:06
  • @PratapJadhavar The compiler will automatically validate the import statement when you deploy the source. The only thing you need to worry about is misspelling files contained in the static resource.
    – sfdcfox
    Commented May 30, 2020 at 16:45
  • Thanks for your reply @sfdcfox. But Not static resource name but the image name inside that static resource is misspells then. For example Einstein.png is the name of image as given above what happens if that image name is misspells. I want like if it is misspells or image is not there then show some default image. So have got solution like by checking valid image url we can render default image or given image. If any other way is there i will be happy to know. Commented May 30, 2020 at 17:09
10

I want to thank sfdcfox for his answer. Officially, dynamic resource loading is not supported. But I threw together a hack in case others need a similar solution.

Setup

Let's say you have a specific static resource format: Market_Resources_xx, where xx is some country code. Below is an example list:

  • Market_Resources_CA
  • Market_Resources_US
  • Market_Resources_DE

Solution

Create a generic static resource, called Market_Resources and fill it with whatever files/data you want. Then create your Market_Resources_xx static resources that will be used within your code.

In your LWC code, you will import the generic static resource and append the additional country code to the variable. See code below:

// Import the generic static resource. All this does is provide a URL to the resource.
import MarketResources from '@salesforce/resourceUrl/Market_Resources';

// ...
// Omitting code for simplicity.
// ...

// We can build our specific to the static resource, dynamically.
const countryCode = getCountryCode();
const resourcePath = `${MarketResources}_${countryCode}/path/to/resource.png`;

// Now we can dynamically load into DOM. For example a background image.
const containerElement = this.template.querySelector('.container');
containerElement.style.backgroundImage = `url('${resourcePath}')`;

Note

Obviously this is a hacky solution. It is error prone if static resources are misspelled but knowing there is a solution for dynamic resources makes me happy :)

1
  • This is very hacky and, unfortunately, broken in LWR sites, which used Static Resource record Ids rather than names.
    – JDB
    Commented Aug 21, 2023 at 16:41
5

Adding my two cents.

In a recent project I was working on, I was iterating over a list of products, which I wanted to display to the user (including the image). The parent lightning web component was rendering the products using a basic 'template for:each for:item'. Each one of those product records had a custom field (Static_Resource__c) with the name of the file.

I used a child lightning web component and passed down the Static_Resource__c value from the parent via the @api decorator, so that I could contain the html and product-specific info in one component and didn't have to do any innerHtml stuff.

The childComponent.js basically looked like this:

import { LightningElement, api, track } from 'lwc';
import PRODUCT_IMAGES from '@salesforce/resourceUrl/productResources';

export default class ProductImage extends LightningElement {
    @api staticResourceName;
    @api amazonLink;
    @track staticResourceUrl;

    connectedCallback(){
        this.staticResourceUrl = PRODUCT_IMAGES + '/pr/' + 
        this.staticResourceName;
    }
}

PRODUCT_IMAGES is a zip file, so all I had to do was pass down the specific file name to access that image. This solution was still a pain having to manage all of the images in the zip file, as well as updating the records. But since I was dealing with <40 products and I never had to update the links/files, it was a one-and-done grind.

Hopefully this helps someone out there. One note of caution, this might not be an acceptable solution if you have tons of products. I'm sure that loading a zipped static resource over and over again isn't great, but it works if you don't have a huge list.

1
  • Thank you for this @Thomas!
    – Tyler
    Commented Aug 19, 2021 at 2:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .