2

I've uploaded a minified pdf.js file (CDN link) into a static resource, but when trying to use it, pdfjsLib is undefined no matter what I try. It was my unstanding that pdfjsLib would be defined and exported in the imported script file, and that Salesforce would attach the export onto the window object. What is possibly going wrong here?

import { LightningElement, api } from 'lwc'
import { loadScript } from 'lightning/platformResourceLoader'
import pdfjs from '@salesforce/resourceUrl/pdfjs'

export default class PdfRender extends LightningElement {

    async renderedCallback() {
        try {
            await loadScript(this, pdfjs)
            console.log(window.pdfjsLib) // undefined
        } catch (e) {
            console.error('There was an issue loading PDF.js: ' + e.message)
        }
    }
 }
1

1 Answer 1

0

Try loading the static resource in the connectedCallback method?

If that doesn't work try with resource loader.

Create a resource loader component (resourceLoader)

/**
 * Utility function to load a JS file via a script tag.
 * @param {String} url - The path to the JS file.
 * @return {Promise} - A promise resolved once the JS file has been loaded.
 */
export function loadScript(url) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        script.charset = 'utf-8';
        script.type = 'text/javascript';
        document.head.appendChild(script);
        script.addEventListener('load', resolve);
        script.addEventListener('error', reject);
    })
}

Import resourceLoader and load static resource in your lwc.

import { loadScript } from 'c/resourceLoader';
                    
connectedCallback(){
    Promise.all([
                //You may have to tweak the following url, try opening the final url in your browser and see if the file loads
                loadScript('/resource/'+yourresourceid+'/something.js')
            ]).then(()=>{

        //Do something after loading your script
    });
}

How to find resource id from salesforce

3
  • Can I ask what the reasoning behind these suggestions is? I'm all out of ideas myself, but I'd still like to know what the functional difference might be between these approaches and mine.
    – upjosh
    Commented Jun 15 at 18:48
  • The main difference is using salesforce platform resource loader vs injecting script tag that reference your static resource via url. I'm trying to avoid any restrictions that the lwc platform resource loader may put when loading external scripts. Commented Jun 17 at 20:56
  • Interesting. Because my original solution loads a static resource and doesn't use a script tag. The only difference with your solution as far as I can see is that you're doing it in a separate component.
    – upjosh
    Commented Jun 18 at 12:11

You must log in to answer this question.

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