0
votes

I am trying to load the jquery library programmatically on my webpart .ts file.

This code works and loads jquery:

import { SPComponentLoader } from '@microsoft/sp-loader';
import * as $ from 'jquery';

export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> {

public render(): void {

SPComponentLoader.loadScript('//code.jquery.com/jquery-3.4.1.slim.min.js', 
                         {globalExportsName: '$'});

But when I modify the loadScript code as follows

SPComponentLoader.loadScript( '//code.jquery.com/jquery-3.4.1.slim.min.js',
{globalExportsName: '$'}).then(() => 
{
  alert($('a').length);
} );  

I am getting the following error

[SPLoaderError.loadComponentError]: ***Failed to load component "c2e267f8-8b0c-47d5-ba20-ba7d151da675" (HelloWorldWebPart). Original error: ***Failed to load entry point from component "c2e267f8-8b0c-47d5-ba20-ba7d151da675" (HelloWorldWebPart). Original error: Error loading https://component-id.invalid/c2e267f8-8b0c-47d5-ba20-ba7d151da675_0.0.1 Cannot find module "jquery"

I think the root of the problem is the following code

alert($('a').length);

is getting executed before the jquery library is fully loaded.

Any ideas on how this issue can be fixed will be appreciated.

2

2 Answers

0
votes

You may try this.

SPComponentLoader.loadScript('https://code.jquery.com/jquery-2.1.1.min.js', {
              globalExportsName: 'jQuery'
            }).then(($: any) => {
              var jQuery = $;
              //jQuery("") function
            })
0
votes

Your code worked, thanks!

SPComponentLoader.loadScript('https://code.jquery.com/jquery-2.1.1.min.js', {
          globalExportsName: 'jQuery'
        }).then(($: any) => {
          var jQuery = $;
          alert($('a').length);
}) ;