Reference Javascript in a Display Template for SharePoint 2013

Introduction

The following guide outlines one of the ways we can reference javascript and load jquery libraries from a display template.

Loading Javascript Files

When loading javascript files, we have two options:

  1. $includeScript
  2. SP.SOD.registerSod

The recommended method going forward is to use SP.SOD.registerSod. With $includeScript, this is loaded asynchronously so we can’t guarantee that the files will be loaded BEFORE the content is ready to go. SP.SOD.registerSod guarantees that the script is loaded when it’s needed for us. I’ll show in the next section how that’s done. Please note that if you have a dependency where one file relies on the other, as is the case with my trunk8 plugin below, you must also use SP.SOD.registerSodDep.

SP.SOD.registerSod('jquery-1.7.1.min.js', this.L_Menu_BaseUrl + "/_catalogs/masterpage/Preview Images/jquery-1.7.1.min.js");
SP.SOD.registerSod('trunk8.min.js', this.L_Menu_BaseUrl + "/_catalogs/masterpage/Preview Images/trunk8.min.js");
SP.SOD.registerSodDep('trunk8.min.js', 'jquery-1.7.1.min.js');
$includeCSS(this.url, "~sitecollection/_catalogs/masterpage/Preview Images/bns.dl.search.css");

Setting Up Your Javascript

Now that you have your script tag configured, you want to setup your custom javascript so that it’s called after all the content has completely loaded within the display template.

// This function will only be called when trunk8.min.js is loaded, which is only happening at page load using the script tag above.
SP.SOD.executeFunc("trunk8.min.js", null, function() {
    console.log("SP.SOD.executeFunc called");
 
    setupTrunk8();
});
 
// This function will be called on page load AND every time the search results are rendered - so on new searches.
AddPostRenderCallback(ctx, function() {
    console.log("AddPostRenderCallback called");
 
    // safeguard to prevent errors as this will run prematurely on page load.
    // but will also be run after fetching search results - in which jQuery will be loaded.
    if(typeof $ == 'undefined') {
        return;
    }
 
    setupTrunk8();
});

,

No comments yet.

Leave a Reply