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/jquery@2.0.48 --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?

  • If you have installed jquery locally in your package then why are you still giving cdn path in config.json?? – Ganesh Sanap Jul 3 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? – JJD Jul 3 at 8:56
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
    });
});
  • Perfect, thanks so much! – JJD Jul 4 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.