Referencing JavaScript libraries in your expressions

Document created by daniel_wyss_(skybow) Employee on Jun 27, 2017Last modified by daniel_wyss_(skybow) Employee on Jun 27, 2017
Version 2Show Document
  • View in full screen mode

The expression language used in skybow Rich Forms and Action Links is very powerful because it allows you to use any JavaScript code. In many cases you might not want to implement all the JavaScript code yourself but reuse some JavaScript libraries. As an example handling dates with the standard JavaScript functions is quite restricted, so using a library like moment.js is very helpful.

But how to include an external JavaScript library (or any JavaScript file in fact) to be used in your expressions?

 

You could add the following to a Script Editor web part on the page or form your expression is needing this library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

That works fine in most cases, but can cause some timing issues if it is not loaded before the expression is executed. Also it will be loaded every time the form or page is opened, which is unnecessary if your expression is not called every time.

 

So a better solution is to use the following inside a function expression:

{
  var url = "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js";
  var fileName = "momentjs";
  var moduleCache = window.module;
  var defineCache = window.define;
  window.module = undefined;
  window.define = undefined;
  window.SP.SOD.registerSod(fileName, url);
  window.LoadSodByKey(fileName, null, true);
  window.module = moduleCache;
  window.define = defineCache;
  // Do your stuff here...
  return window.moment().format();
}

This will load the momentjs library before running your code where you can use it as you want (returning "window.moment().format()" is just an example).

In case your wondering: The whole handling of module and define is only needed if we have a js library that works with requirejs, like momentjs. But it won't disturb for other libraries too.

Of course you can use any URL to your js file and change the fileName appropriately.

 

Making including JavaScript libraries in expressions even easier is on our roadmap, but for the moment using the approach above should get you there.

Attachments

    Outcomes