Sharepoint Framework doesn't run jquery in .js file
-
07-02-2021 - |
Question
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?
Solution
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
});
});
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange