1

After wasting significant amount of time on how to import jQuery, I got below 2 ways in HTML with local path or CDN:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

IN JS with local path or CDN:

var script = document.createElement('script');
script.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);

But unfortunately both of the above methods won't work in LWC and there is no documentation available on how to do the same.

Below approach works fine in my index.html page to import jQuery in my lwc project.

<script src="./resources/js/jquery-3.5.1.min.js"></script>

I also wasted so many hour on how to import CSS in lwc as there is no documentation available on importing third party CSS also but some how I manged to import css by using below code

constructor() {

    super();

    const styles = document.createElement('link');
    styles.href = './resources/css/bootstrap.css';
    styles.rel = 'stylesheet';
    this.template.appendChild(styles);
}

So I tried some similar approach to import JS and this doesn't give any errors at the console log but the same doesn't work at all, tried in both constructor and connectedCallback but no luck.

connectedCallback() {
        const jq = document.createElement('SCRIPT');
        jq.src = './resources/js/jquery-3.5.1.min.js';
        jq.type = 'text/javascript';
        this.template.appendChild(jq);
    }

if anyone has any idea about how to import the JS library in open source LWC then please do let me know, would highly appreciate your help.

gs650x
  • 383
  • 2
  • 22
  • In what way is it not working? – Ouroborus Aug 16 '20 at 17:48
  • I mean anything related to jQuery works in my index.html as this is standard html but the same doesn't work in my app.html which is not standard html page but a lightning component. – gs650x Aug 16 '20 at 17:54
  • I am trying to use bootstrap carousal whcih need jQuery, the same works as expected in my index.html but not able to slide the same in my app.html – gs650x Aug 16 '20 at 17:55
  • I have updated my question with more details, please let me know if I am doing something wrong. – gs650x Aug 16 '20 at 17:56
  • There's a stackexchange for Salesforce and LWC is a feature of Salesforce. Maybe [this](https://salesforce.stackexchange.com/questions/279897/best-way-to-use-jquery-on-lighting-web-components) helps? – Ouroborus Aug 16 '20 at 18:02
  • Yes, I have posted my question there but didn’t get any reply so posted it here – gs650x Aug 16 '20 at 18:03

2 Answers2

1

I know this is way too late to answer for the OP but Salesforce blocks third party script references even if it is added to the CSP Trusted Sites. They state you must manually download and upload as a static resource as of this post.

The framework’s content security policy mandates that external JavaScript libraries must be uploaded to Salesforce static resources. For more information on static resources, see “Static Resources” in the Salesforce online help.

Source: developer.salesforce.com

interesting-name-here
  • 1,851
  • 1
  • 20
  • 33
-1

First thing that we need to do is to add the JQuery JS file in the Static Resource. The Static Resource should look something like below:

JQuery Static Resource

Include JQuery in LWC (Lightning Web Component)

In the JS Controller, we first need to import loadScript() method from
lightning/platformResourceLoader module. We can also include loadStyle method if we want to include an external CSS file.

import { loadScript, loadStyle } from 'lightning/platformResourceLoader';

Import the Static Resource that we created earlier as well. Check this implementation to include Static Resource in Lightning Web Component.

Finally, in the renderedCallback method, call loadScript that we imported earlier and pass a reference to the current template (this) and the Static Resource. This method returns the Promise. The then() function will be called if the Promise is resolved. The catch() function will be executed if there is an error. We are using renderedCallback as we want to load the Scripts once the component is loaded and rendered on UI.

Now, to access the JQuery method in Lightning Web Component, there is some catch. Ideally, there are multiple ways to call JQuery methods. The most common one is below:

$(".className").hide();

This will hide the element with class=”className”. But in Lightning Web Component, we must use it like below:

$(this.template.querySelector('.className')).hide();

That is all. We just need to reference the elements using queryLocator. Then, we can call the JQuery methods.

   import { LightningElement } from 'lwc';  
   import { loadScript, loadStyle } from 
   'lightning/platformResourceLoader';    
   import jQuery from '@salesforce/resourceUrl/JQuery';  

lwcJquery.js

   import { LightningElement } from 'lwc';
   import { loadScript, loadStyle } from 
   'lightning/platformResourceLoader';
   import jQuery from '@salesforce/resourceUrl/JQuery';

   export default class LwcJquery extends LightningElement {

    renderedCallback(){
    loadScript(this, jQuery)
    .then(() => {
        console.log('JQuery loaded.');
    })
    .catch(error=>{
        console.log('Failed to load the JQuery : ' +error);
    });
    }

    slideIt(event){
    $(this.template.querySelector('.panel')).slideToggle("slow");
    }

    slideRight(event){
    $(this.template.querySelector('.innerDiv')).animate({left: 
    '275px'});
    }
    }

Here, I have used slideToggle() and animate() JQuery methods to add some animation.