Thursday, May 22, 2014

Run custom script after display templates render

Share/Save/Bookmark
I have been trying to run some custom javascript after $(document).ready in sharepoint control display template and stuck very badly.No matter where i place the js code in the display template(html) file, DOM is not ready by the time document.ready executes. So elements references in the script always return null. It seems that DOM rendering and the way MS handled events is different in the case of the display templates.

Exploring other templates, figured out that below code works when added to control display template. Bind the function that need to be called with OnPostRender event on the ClientContext object, ctx(instantiated by sharepoint)

ctx.OnPostRender = [];

ctx.OnPostRender.push(function () {
   alert("Document is ready");
  // logic goes here
});

In the above code post render callback is used to call custom script that will run after every script is called and complete DOM is rendered in display template.
OnPostRender = $(document).ready when working with sharepoint display templates. No more scratching.
Custom logic can be moved to an external file and refered in the display template as below or call it by using SP.SOD functions,

$includeScript(this.url, https://sharepointcustomization.blogspot.com/js/jquery.min.js);

Subscribe

1 comment:

  1. This is really interesting and knowledgeable. Thanks for sharing. I really appreciate it a lot. Please do more blogs in the future. Thank you and God bless to the blogger!

    Rica
    www.imarksweb.org

    ReplyDelete