0

I'm starting out with Sharepoint framework and at this point I just want to play around and get familiar with the concepts.

I've created webparts with the Yeoman generator and launched them in the workbench. Then I installed jquery 'by the book' but when I try to run a script from another file, it doesn't run the jquery code. The jQuery inside the webpart.ts runs fine. What's going on ?

i've installed jquery using:

npm install @types/[email protected] --save

config.json

  ...
  "externals": {

    "jquery": "https://code.jquery.com/jquery-2.2.4.min.js",
    "myScript":{
      "path": "./src/test.js",
      "globalName": "myScript"

    }
...

webpart.ts

...
import * as $ from 'jquery';
require('myScript');
...
public render(): void {
this.domElement.innerHTML = `
<div id='testDiv'>Not Changed?</div>
<div id='testDiv2'>Not Changed?</div> `
;


$(function(){
  $("#testDiv").html("Changed") // works
});

test.js

console.log("hi"); // this is logged
$(function(){  // error: $ is not defined
    console.log( $("#testDiv2").html());  
    $("#testDiv2").html("Changed")
});

It seems the script in the .js file runs before the innerhtml is rendered? How does this work?

2
  • If you have installed jquery locally in your package then why are you still giving cdn path in config.json?? Commented Jul 3, 2019 at 7:59
  • Hi Ganesh thanks for your reply. I'm new to the framework and simply followed the steps in the book. How would I use the local file instead of the cdn? I can't find a file in the folder structure. Also - will this solve the issue I am facing? Commented Jul 3, 2019 at 8:56

1 Answer 1

1

Try to use SPComponentLoader:

import { SPComponentLoader } from '@microsoft/sp-loader';

Now you can load your external script inside render() method (or somewhere else), like this:

SPComponentLoader.loadScript('https://code.jquery.com/jquery-2.2.4.min.js', {
    globalExportsName: 'jQuery'
}).then(($: any) => {
    $(function() {
        console.log('jQuery is loaded');
    });
    SPComponentLoader.loadScript('path_to_script', {}).then(() => {
        //...do something
    });
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.