Loading dependent JS files (e.g. JQuery Plugins) into SPFx Solution in right order

Today I want to show you quick solution how you could load multiple dependent JS files into your SPFx Solution (in my example SPFx Web Part) in right order.

Lets imagine that we have to make simple Weather SPFx Web Part. We decided to use JQuery plugin named SimpleWeather which is based / it depends on JQuery. If you want your Web Part to work normally at each loading time you have to take care on loading order of your external JS script files.

So we have to include this two script files into our SPFx Web Part solution:

  • jquery-2.1.1.min.js
  • jquery.simpleWeather.min.js

Firstly you have to include it as external scripts into config.json SPFx config file:

"externals": {
    "jquery": {
      "path": "https://code.jquery.com/jquery-2.1.1.min.js",
      "globalName": "jQuery"
    "simpleWeather": {
      "path": "https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js",
      "globalName": "jQuery",
      "globalDependencies": [ "jquery" ]

After that you could use ES6 import or require() statement:

import * as jQuery from 'jquery'; 

In theory this should work. But not always. In some cases could be jquery.simpleWeather.min.js loaded faster than jquery-2.1.1.min.js file because JS files are loaded / imported simultaneously.

So, example above is not good.
You have to take care of loading order. This should be done by example below which is better solution:

SPComponentLoader.loadScript('https://code.jquery.com/jquery-2.1.1.min.js', {
  globalExportsName: 'jQuery'
}).then(($: any) => {
  this.jQuery = $;
  SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js', {
    globalExportsName: 'jQuery'
  }).then(() => {
    // after all JS files are successfully loaded
    // ...

In code above we use SPComponentLoader from @microsoft/sp-loader module which works on SharePoint 2016 on-prem too.

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

If you are not limited with SharePoint 2016 on-prem you could use ModuleLoader instead:

import ModuleLoader from '@microsoft/sp-module-loader';


Gašper Rupnik


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: