Script On Demand: A New Method For Running Javascript In Sharepoint

The Problem: Limited JavaScript Execution in SharePoint

SharePoint pages traditionally only execute JavaScript code during the initial page load process. There is no built-in way to run additional JavaScript functions on demand after the page has loaded.

This limited execution model is problematic for developers who want to build dynamic SharePoint solutions. With no ability to execute code on demand, developers are forced to choose between inefficient full page reloads or clunky workarounds like hidden iframes.

Common use cases that are difficult or impossible with limited JavaScript execution include:

  • Dynamically updating the UI after data changes
  • Calling SharePoint client APIs like the REST API
  • Validating forms without doing a full postback
  • Loading data dynamically from external sources

A more robust JavaScript execution model is needed to deliver modern solutions and experiences in SharePoint.

Introducing Script on Demand

SharePoint 2013 introduced a new feature called Script on Demand (SOD) to overcome the limitations of traditional SharePoint JavaScript execution.

Script on Demand allows developers to register JavaScript files that can be executed on demand after the page has loaded. It provides a structured way to call JavaScript functions asynchronously without needing to reload the entire page.

Key capabilities provided by Script on Demand include:

  • Register scripts to be loaded and executed later
  • Execute registered scripts whenever needed
  • Asynchronously load script dependencies
  • Avoid costly full page reloads

This on demand execution model unlocks many new opportunities for dynamic and responsive solutions in SharePoint.

How Script on Demand Works

Understanding how Script on Demand works under the hood can help in designing effective solutions.

At a high level, Script on Demand allows developers to register JavaScript files and associate functions within those files that can be executed later on demand.

When pages load, any registered scripts are added to the page but are not executed yet. The registered scripts and functions are held in memory to be called later.

Execution of specific functions happens asynchronously by calling SP.SOD.executeFunc() and passing the function name. Script on Demand handles loading any required script dependencies and executes the function as soon as dependencies are loaded.

By separating script loading from execution, Script on Demand enables calls to JavaScript functions precisely when needed without needing synchronous dependencies or full page reloads.

Registering Scripts for On Demand Execution

To leverage Script on Demand, scripts must first be registered via SP.SOD.registerSod(). Registration tells SharePoint which scripts can be executed later on demand.

The registerSod method accepts three parameters:

  • A unique name for the script
  • Path to the JavaScript file
  • The function to execute from the script

Optionally, a fourth arrays parameter can specify any dependencies required before executing the passed function.

Here is an example Script on Demand registration:

SP.SOD.registerSod('myScript', '/scripts/myScript.js', function() {
    runMyFunction();
}, [otherScript1, otherScript2])

This registers a unique script called “myScript”, located at the passed file path. When executed later, it will call the runMyFunction() function defined in myScript.js. That function depends on otherScript1 and otherScript2 already having loaded.

Example Script Registration

Here is a more complete example of registering a script for on demand execution in SharePoint.

First, a sample function is defined in a custom JavaScript file. This function fetches data from a SharePoint list and processes it:

// myScript.js

function runMyFunction() {

  var siteUrl = '/sites/mySite';  

  getListData(siteUrl + '/myList').then(function(data) {
    
    // Process list data
    var processed = processData(data);  
    
    // Additional actions with processed data  
    updateUi(processed);

  });

} 

Next, the script file can be registered for on demand execution:

SP.SOD.registerSod('myAppScript', '/scripts/myScript.js', runMyFunction);

This registers myScript.js and associates it with the runMyFunction() function defined in the file. By calling executeFunc later and passing ‘runMyFunction’, SharePoint will know how to load and run this script on demand.

Executing Registered Scripts

After scripts have been registered, their associated functions can be executed anytime using SP.SOD.executeFunc.

executeFunc takes the unique function name registered earlier as its first parameter. Any additional parameters will be passed to the function when it is called.

Here is an example executing the runMyFunction script from the previous example:

 
SP.SOD.executeFunc('myAppScript', 'runMyFunction');

Behind the scenes when this executeFunc call happens, Script on Demand handles several steps automatically:

  1. Checks if myAppScript is already loaded, and loads it if needed
  2. Checks if dependencies like JQuery or other registered scripts are loaded
  3. Asynchronously loads any required dependencies
  4. Executes the runMyFunction() function once loaded

This automated handling of script loading and dependency management is what makes Script on Demand so convenient to use.

Common Use Cases

Now that the basics of registering and calling scripts are covered, let’s explore some of the ways Script on Demand can be used in SharePoint solutions.

Dynamically Updating the UI

One of the most common uses of Script on Demand is to update areas of the UI dynamically in response to user actions.

For example, when the user changes the value in a dropdown, Script on Demand could execute without reloading the page to update related data elsewhere on the screen.

$('#myDropdown').change(function() {

  var selectedValue = $(this).val();  

  SP.SOD.executeFunc('updateUIScript', 'updateRelatedData', selectedValue);

})

Calling SharePoint REST APIs

Script on Demand opens the door to accessing SharePoint data and services in custom scripts. SP.SOD.executeFunc can call SharePoint REST API endpoints to create, read, update, and delete data.

A registered script could use the REST API to look up user profile information to then update the UI or perform other actions.

function getUserProfileData() {

  var url = '/_api/SP.UserProfiles.PeopleManager/GetMyProperties';

  $.getJSON(url, function(data) {
  
    // Do something with user profile data 
    
  });

}

Validating Forms Dynamically

For long or complex SharePoint forms, validating every field on form submission can impact performance. Script on Demand allows validating inputs dynamically as users update fields.

  
$('#firstName').change(function() {

  // Value updated, validate immediately
  
  var valid = validateFirstName(this.value);
  
  if(!valid) {
     showValidationError(); 
  }
  
});

This helps catch issues immediately without waiting for a full form postback.

Considerations and Limitations

While powerful, Script on Demand does come with some limitations to keep in mind.

First, it requires more planning and overhead than basic embedded script tags. All executeFunc dependency chains must be registered upfront before calling.

Second, Script on Demand scripts are not as easy to debug using browser dev tools since they execute asynchronously. Special debugging techniques may be needed.

Finally, pages with very frequently changing script requirements are less suited for Script on Demand. The registration overhead could become burdensome.

However, for most medium to large SharePoint solutions, Script on Demand delivers tremendous benefits for creating dynamic, data-driven user experiences in SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *