Page 1 of 1

What is the best way to load external scripts

Posted: 17 Dec 2018
by andyb
I need a couple of additional javascript libraries for some fairly complex form functionality - can you advise the best way to load external js scripts so that they become available to the whole form?

Should I be adding code into the new/edit/display form .aspx page in SharePoint Designer? Or should I load these within the form itself once the fd object has rendered?

Finally, I also use JSLink to modify some columns within some child lists and libraries, how can I make the external libraries also available to them?

I'm using Office 365/SharePoint Online so am a bit nervous about editing any pages, but would like to know what the recommended approach is. Say, for example I wanted to use Moment.js and make that available to everything within the scope of a form, how would I go about this in the correct way?

Kind regards
Andy

Re: What is the best way to load external scripts

Posted: 18 Dec 2018
by AlexZver
Dear Andy,

You can load the external libraries via "$.getScript()" function.

Let's take Moment.js for example. At first, you should upload library files to Sharepoint, e.g. to SiteAssets.

A code for Moment.js will be like this:

Code: Select all

$.getScript("/sitecollection/site/SiteAssets/moment-with-locales.min.js")
.then(function() { return $.getScript("/sitecollection/site/SiteAssets/moment.min.js") })
.then(function() {
    // Place all your code that uses the external library.
})
If you will load only one file, a code slightly changes:

Code: Select all

$.getScript("/sitecollection/site/SiteAssets/moment-with-locales.min.js").then(function() {
    // Place all your code that uses the external library.
})