[SalesForce] How to load jQuery in LWC

For the convenience of the user, I'm implementing the requirement of katakana is automatically entered when entering hiragana or kanji in Japanese using this JavaScript library.

You can check the behavior described above at this URL.

That external JavaScript depends on jQuery, so I have to use jQuery.
First, I'm importing jQuery and trying to see whether it can be used.

I'm trying with a custom component (LWC) in Experience Cloud (Community Cloud).

This Url is my testing community page.

As it, I mentioned before, the question that can't be loaded, but it seems that jQuery doesn't work on the loaded page.

Here is my code to load jQuery at my custom component(LWC).

renderedCallback() {
    loadScript(this, jQueryUrl + '/jquery-3.5.1.min.js')
      .then(() => {
        console.log(`jQuery loaded.`);
      })
      .catch((error) => {
        console.log(`jQuery loading was failed.`);
      });
  }

I tried window.jQuery in the Chrome developer console, but it didn't seem to reference to jQuery.You can check the behavior at this Url.

I confirmed that it is displayed as follows in the developer tools of chrome.You can also check the script tag at my testing community page's in <head> tag.

<script data-locker-src="/resource/***/jQuery/jquery-3.5.1.min.js" type="text/javascript"></script>

How can I solve it?

Best Answer

The issue that you are facing is that LWC is loading libraries within your specific component and isolates it from outside.

So if you try to use it inside the component, you'll be able to write something like $('input'), but window.jQuery in developer console will produce undefined.

Hopefully, this helps.

UPDATE: You can access $ after callback on jQuery loaded. In your code you're trying to call jQuery on renderedCallback when it's not yet loaded.

Try something like this

            connectedCallback() {
                Promise.all([i.loadScript(this, t + "/jquery-3.5.1.min.js").then(()=>{
                    console.log("jQuery loaded."),
                    i.loadScript(this, l + "/jquery.autoKana.js").then(()=>{
                        console.log("autoKana loaded")
                        this.usejQuery();
                    }
                    ).catch(a=>{
                        console.log("autoKana was not loaded. error is " + a)
                    }
                    )
                }
                ).catch(a=>{
                    console.log("jQuery loading was failed.")
                }
                )])
            }


            usejQuery() {
                console.log($(".li-kanji").val()),
                $.fn.autoKana(".li-kanji", ".li-furigana", {
                    katanaka: !0
                })
            }
            renderedCallback() {
            }
            handleLiKanji(a) {
                this.liKanji = a.target.value
            }
            handleIKanji(a) {
                this.iKanji = a.target.value
            }