As always there are different ways to load jQuery or any other JavaScript library. If you read through the tutorials you will soon learn that you can unbundle the library from the webpart itself. This would be useful if you have several webparts on the same page.
Unbundle external dependencies from web part bundle
By default any dependencies you add gets bundled into the web part bundle. While this could be true for some cases, it is not ideal. Hence you can choose to unbundle these dependencies from the web part bundle.
In Visual Studio Code, open the file config\config.json
This config.json contains information about your bundle(s) and any external dependencies included.
The entries region contains the default bundle information which in our case is the jQuery web part bundle. You will see one entry per web part once you add more web parts to your solution.
"entries": [
{
"entry": "./lib/webparts/jQuery/jQueryWebPart.js",
"manifest": "./src/webparts/jQuery/jQueryWebPart.manifest.json",
"outputPath": "./dist/j-query.bundle.js",
}
]
The externals section contains the libraries information that are not bundled with the default bundle. As you can see, we have a few by default.
"externals": {
"@microsoft/sp-client-base": "node_modules/@microsoft/sp-client-base/dist/sp-client-base.js",
"@microsoft/sp-client-preview": "node_modules/@microsoft/sp-client-preview/dist/sp-client-preview.js",
"@microsoft/sp-lodash-subset": "node_modules/@microsoft/sp-lodash-subset/dist/sp-lodash-subset.js",
"office-ui-fabric-react": "node_modules/office-ui-fabric-react/dist/office-ui-fabric-react.js",
"react": "node_modules/react/dist/react.min.js",
"react-dom": "node_modules/react-dom/dist/react-dom.min.js",
"react-dom/server": "node_modules/react-dom/dist/react-dom-server.min.js"
},
In order to exclude jQuery and jQueryUI from the default bundle, we add the modules respectively to the externals section:
"jquery":"node_modules/jquery/dist/jquery.min.js",
"jqueryui":"node_modules/jqueryui/jquery-ui.min.js"
Now when you build your project, jQuery and jQueryUI will not be bundled into your default web part bundle
Reference: jQuery accordion webpart
Once examples go wild, they will be copy/pasted, and 90% of "developers" won't have a clue on what they are doing
, i can't agree more