[SalesForce] How to dynamically load a static resource image in LWC

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}')

Best Answer

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.

Related Topic