Share via


SharePoint 2013: JSLink (Client Side Rendering): OnPreRender Event


Client-side rendering or JSLink is a new concept in SharePoint 2013.  In my earlier article SharePoint2013: JSLink (Client Side Rendering) explained about Client-side rendering or JSLink.

In this article, we are going to use JSLink > OnPreRender Event. With the help of this event, we can perform an action before rendering the view. OnPreRender accepts either a function or an array of them. All provided functions will be executed whenever an event is fired.

We first need to write the definition of the function which needs to be called:

/*
This function has been used to add reference of JQuery framework, if not present
*/
JSLinkSecurity.Functions.AddJQuery = function  (ctx) {
    absoluteSiteUrl = _spPageContextInfo.webAbsoluteUrl;
 
    var siteUrl = window.location.protocol + "//" + window.location.host + "/"; //=>
    // check if jQuery is available, otherwise reload it
    if (!window.jQuery) {
        var jq = document.createElement('script'); jq.type = 'text/javascript';
        jq.src = siteUrl + JQuery_URL;
        document.getElementsByTagName('head')[0].appendChild(jq);
    }
}
 
/*
This function has been called from the FIELDS and 
>using AddJQuery function to add Jquery reference
*/
JSLinkSecurity.Functions.InitiateScopeList = function  () {
    //Add jqery and links
    JSLinkSecurity.Functions.AddJQuery(ctx);
}

In the above functions, we are trying to, dynamically add a reference to jQuery in JSLink (Client Side Rendering) on SharePoint Page. Once List View page loaded, you will be able to see the reference to jQuery File.

JSLinkSecurity.Functions.AddJQuery: This function receives the current context of the page and will add the reference of jQuery file under the head section of the page.
JSLinkSecurity.Functions.InitiateScopeList: This function would be called from OnPreRender event and using JSLinkSecurity.Functions.AddJQuery function to, dynamically add reference of jQuery on SharePoint page.

After that, we need to call the custom function on JSLink > OnPreRender Event:

/*
This function OnPreRender event fires before the DOM is loaded. 
>using InitiateScopeList function
*/
JSLinkSecurity.OnPreRender = JSLinkSecurity.Functions.InitiateScopeList;

Note: One thing, needs to be remembered that before calling the function JSLinkSecurity.Functions.InitiateScopeList,  we need to define it, otherwise, it will not work in JSLink. It means if we will add a definition of JSLinkSecurity.Functions.InitiateScopeList/JSLinkSecurity.Functions.AddJQuery after the above statement then your function would not be called during page load.

Complete Code:

/* This Script can be reference via the List Property of a WebPart to display Title in bold and FirstName in red color
* Version:      0.0.3.1
* Created By:   Amit Kumar
* Modified By:  Amit Kumar
* ChangeDate:   04/04/2017 (MM/DD/YYYY)
*/
 
//----------Declare and Initialze global variables----------::Start::--------------
var CURRENT_CONTEXT = '';
var CURRENT_WEB = '';
var SP_LIST = '';
var JSLink_URL = "/SiteAssets/JSLink_Title.js";
var JQuery_URL = 'sites/amitkumarmca04.blogspot.com/SiteAssets/jquery-3.1.1.min.js';
var CURRENT_FIELD_VALUE = '';
var CURRENT_FIELD_ID = '';
var CURRENT_LIST_TITLE = '';
 
 
 
//----------Declare and Initialze global variables----------::Start::--------------
 
Type.registerNamespace('JSLinkSecurity')
JSLinkSecurity.Templates = JSLinkSecurity.Templates || {}
JSLinkSecurity.Functions = JSLinkSecurity.Functions || {}
 
JSLinkSecurity.Functions.LoadJSCSSFile = function  (filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}
 
/*
This function has been used to add reference of JQuery framework, if not present
*/
JSLinkSecurity.Functions.AddJQuery = function  (ctx) {
    absoluteSiteUrl = _spPageContextInfo.webAbsoluteUrl;
 
    var siteUrl = window.location.protocol + "//" + window.location.host + "/"; //=>
    // check if jQuery is available, otherwise reload it
    if (!window.jQuery) {
        var jq = document.createElement('script'); jq.type = 'text/javascript';
        jq.src = siteUrl + JQuery_URL;
        document.getElementsByTagName('head')[0].appendChild(jq);
    }
}
 
/*
This function has been called from the FIELDS and 
>using AddJQuery function to add Jquery reference
*/
JSLinkSecurity.Functions.InitiateScopeList = function  () {
    //Add jqery and links
    JSLinkSecurity.Functions.AddJQuery(ctx);
}
 
JSLinkSecurity.Functions.ChangeFieldColor = function  (ctx) {
    if (ctx != null) {
        var chkDefaultValue = setInterval(function () {
            if ($('.csrColor').length != 0) {
 
                $('.csrColor').css("color", "red");
                clearInterval(chkDefaultValue);
 
                 
            }
        }, 100);
    }
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//**********************Minimal Download Strategy(MDS) code block and JSLink code block**************::Start::***************
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
 
/*
This function  OnPreRender event fires before the DOM is loaded. 
>using InitiateScopeList function
*/
JSLinkSecurity.OnPreRender = JSLinkSecurity.Functions.InitiateScopeList;
 
JSLinkSecurity.OnPostRender = JSLinkSecurity.Functions.ChangeFieldColor;
 
 
/*
This function has been used to override the content of list view form for each field
*/
JSLinkSecurity.Functions.OverRideViewMode = function  (ctx) {
    var result = '';
 
    if (ctx != null && ctx.CurrentItem != null) {
        CURRENT_FIELD_VALUE = '';
        CURRENT_FIELD_VALUE = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
        CURRENT_FIELD_ID = ctx.CurrentItem.ID;
        CURRENT_LIST_TITLE = ctx.ListTitle;
        result = '<strong>' + ctx.CurrentItem.Title + '</strong>';
        return result;
    }
}
 
/*
This function has been used to override the content of list view form for First Name field
*/
JSLinkSecurity.Functions.OverRideFNameField = function  (ctx) {
    var result = '';
 
    if (ctx != null && ctx.CurrentItem != null) {
        result = "<span class='csrColor'>"  + ctx.CurrentItem.FirstName + "</span>";
        return result;
    }
}
 
 
 
/*
This function has been used to override the override the field inlist view form
*/
 
JSLinkSecurity.Templates.Fields = {
    'Title': {
        'View': JSLinkSecurity.Functions.OverRideViewMode
    },
    'FirstName': {
        'View': JSLinkSecurity.Functions.OverRideFNameField
 }
}
 
 
/*
This function has been used to register the namespace as per Minimal Download Strategy(MDS)
*/
JSLinkSecurity.Functions.RegisterField = function  () {
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(JSLinkSecurity)
}
 
/*
This function has been used to register the JS file as per Minimal Download Strategy(MDS)
*/
JSLinkSecurity.Functions.MdsRegisterField = function  () {
    var thisUrl = _spPageContextInfo.webServerRelativeUrl + JSLink_URL;
    JSLinkSecurity.Functions.RegisterField();
    RegisterModuleInit(thisUrl, JSLinkSecurity.Functions.RegisterField)
}
 
/*
This code block used to find Minimal Download Strategy(MDS) enabled on the site or not
>on the basis of that it's registring the JS file
*/
if (typeof _spPageContextInfo != "undefined" && _spPageContextInfo != null) {
    //-- MDS enabled on our site
    JSLinkSecurity.Functions.MdsRegisterField()
} else  {
    //-- MDS no enabled on our site
    JSLinkSecurity.Functions.RegisterField()
}
 
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//**********************Minimal Download Strategy(MDS) code block and JSLink code block**************::End::***************
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

In the above code block, we already implemented the logic to display JSLink changes in Minimum Download Strategy (MDS) feature enabled site. By default MDS is enabled in SharePoint 2013 Team sites. For more detail check article  SharePoint2013: JSLink (Client Side Rendering) .