Issues with javascript/jQuery in Application Customizer - timing issue

Copper Contributor

Hi

I am trying to add javascript and css to my Sharepoint Online/Modern site using Application Customizer for the first time.

 

In my ApplicationCustomizer.ts, I try tlo load jquery and my oqn javascript from site assets using this code (I add a date/time string to avoid the page using cached javascript)

 

    let current_date: Date = new Date();
    let date_String: string = current_date.toString();
    date_String = current_date.toISOString()
    console.log('date_string = %s', date_String);
    SPComponentLoader.loadCss('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.css?d=' + date_String);
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/jquery-3.6.3.min.js?d=' + date_String)
    SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.js?d=' + date_String);

 

 
I also added the datestirng to jquery as I read it was how to force the javascript to load in the specified order.
 
My main javacript ((caj23.js) then uses jquery $(document).load() to run some code - however, this only works intermittently. When it fails, the console shows 

 

caj23.js?d=Mon%20Jan%2009%202023:50 Uncaught ReferenceError: $ is not defined​

 

which suggests jquery hadn't finished loading in time before the $(document).load() fired.
 
Is there any way to force the my javascript to wait until jQuery is ready? 
Or some other way to fix dependencies?
 
Thanks!
 
1 Reply
SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/jquery-3.6.3.min.js?d=' + date_String, {
globalExportsName: 'jQuery'
}).then(($: any) => {
$(function () {
console.log('jQuery is loaded');
});
SPComponentLoader.loadScript('https://8lbg15.sharepoint.com/sites/KnowledgeBase/SiteAssets/caj23.js?d=' + date_String, {}).then(() => {
//...do something
});
});