Best Practices For Using Sp.Sod.Executefunc And Executeordelayuntilscriptloaded

Why Scripts Load Slowly on SharePoint Pages

SharePoint pages rely heavily on asynchronous JavaScript loading to populate components. However, this approach leads to sluggish performance and browser hangs when key dependencies are not handled properly. Understanding the asynchronous nature of SharePoint script loading can help optimize page interactions.

Asynchronous Nature of Script Loading

SharePoint script files do not block other page loading when requested. This asynchronous loading seems responsive at first, but can cause major delays if later scripts depend on earlier ones to complete. Developers must sequence and structure code to avoid race conditions between interdependent scripts.

Dependencies Between Scripts

Many SharePoint components rely on specific scripts to be available before initialization. For example, the ClientPeoplePicker.js must load before the related People Picker can render and function. Without considering these ordered dependencies, async scripts may attempt to interact with undefined objects and methods, failing silently.

Solutions for Async Script Issues

Tools like SP.SOD.executeFunc and ExecuteOrDelayUntilScriptLoaded allow developers to explicitly control script loading and interaction sequencing. These methods delay code execution until specific prerequisites are loaded, or safely wrap logic depending on those scripts to prevent errors. Applying these solutions improves page performance and stability.

Using SP.SOD.executeFunc to Control Script Execution

Basic Syntax and Usage

The SP.SOD.executeFunc accepts two parameters – the name of a script file, and a callback function to run when loaded. For example:
SP.SOD.executeFunc(‘script.js’,’ScriptLoaded’);
This ensures any code inside the ScriptLoaded function is only called once script.js has finished loading asynchronously, preventing incorrect assumptions or interaction attempts by other dependent scripts which may have loaded sooner.

Example Calling External Function After Script Loads

SP.SOD.executeFunc is often used to call functions defined inside the loaded script, which only exist once asynchronously available. For example:

“`js
SP.SOD.executeFunc(‘componentScript.js’, ‘ComponentScriptLoaded’);

function ComponentScriptLoaded() {

// Safe to call ComponentScript functions now

var component = new ComponentScript.MyComponent({options});
component.render();

}
“`
This safely instantiates and renders the component without risk of errors from the object or method not being loaded yet when initially called.

Implementing ExecuteOrDelayUntilScriptLoaded

Syntax for ExecuteOrDelayUntilScriptLoaded

ExecuteOrDelayUntilScriptLoaded takes the script file name to check, a function to run once loaded, and an optional duration to retry loading the script before failing as parameters:

“`js
ExecuteOrDelayUntilScriptLoaded(‘script.js’, scriptLoadedCallback, 5000);
“`

This method continually checks if the script is loaded until successful, then calls the callback. The duration parameter gives a timeout threshold before rejecting if the script cannot load.

Delaying Code Execution Until Script Loads

A simple use case isdelaying any logic dependent on the script until verifying it has loaded. For example:

“`js
ExecuteOrDelayUntilScriptLoaded(‘charts.js’, function() {

// Safe to initialize and render charts now

var salesChart = new Charts.ColumnChart(data, options);

}, 10000);
“`

This pattern prevents errors from attempting to use APIs and objects from the charts library before that script finishes loading asynchronously.

Example Using Promise from Loaded Script

Loaded scripts often expose Promise-based APIs as well. We can await these inside the callback:

“`js
ExecuteOrDelayUntilScriptLoaded(‘userProfile.js’, async function() {

// Await promise-based method once ensured loaded

let profile = await UserProfile.getCurrent();

displayProfile(profile);

}, 5000);
“`

This takes full advantage of the underlying asynchronous APIs, while safely adding guarantees around initialization.

Tips for Handling Script Dependencies

Plan Order of Script Loading

Map out any chained dependencies between required scripts and background services. Then structure code and page loading to address these in the correct sequence. Building this sequence diagram helps guide architecture decisions.

Manage Script Interactions

Use wrappers like SP.SOD.executeFunc and ExecuteOrDelayUntilScriptLoaded during interactions between scripts with order dependencies. This isolates failures instead of blocking entirely.

“`js
SP.SOD.executeFunc(‘charts.js’, function() {

ExecuteOrDelayUntilScriptLoaded(‘data.js’, function() {

// Safe to initialize with ordered dependencies met

});

});
“`

Load Scripts Early to Prevent Lag

Start loading dependent scripts as early in page load as possible, using document ready handlers and other triggers to kick off requests before associated components load. This builds a buffer minimizing perceivable lag from loading these scripts on demand later.

Summary – SP.SOD Helpers for Better Performance

SharePoint’s asynchronous script loading behavior leads to tricky dependency issues. SP.SOD.executeFunc and ExecuteOrDelayUntilScriptLoaded give control for sequencing execution based on script availability. This equates to faster, more resilient page loading and interactions when leveraged properly.

Leave a Reply

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