11

This is the issue:

  1. I create a ContentBySearchWebpart, specified with my custom Display templates.'
  2. I want to run some other javascript code, after the Display Templates have rendered the content
  3. I then register my custom javascript file in Display template.

            $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Slider.js")'
    

    The problem is that my Slider.js file code executes before the 'Display Templates' Javascript code does.

Can anybody provide me a way to execute my Slider.js code after the display templates have rendered the content of ContentBySearchWebpart(CSWP)?

2 Answers 2

19

:) my issue is solved.

I did following:

  1. Registered the custom JS file in Control_YourTemplateName.html file(like Control_Banner).

    $includeScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/HWScripts/Banner.js");

  2. Added these three lines under the first div after body tag, in YourTemplateName.html (like Banner.html) file.

     <!--#_  
     ctx.OnPostRender = [];
     ctx.OnPostRender.push(function(){ 
        CustomMethodWhichIsIncludedInTheCustomJSFile();
     });
     _#-->  
    

But a better solution is provided below:

You can skip defining OnPostRender yourself. CBS Display Templates have this function baked in:

<!--#_
   AddPostRenderCallback(ctx, function(){
       alert(ctx.Title + "finished rendering!");
   });
_#-->

There is also AddPreRenderCallback(ctx, function(){});

2
  • Yes it is better :) May 6, 2013 at 13:16
  • Is there a way to add the post render function from outside the template? For example I have a code snippet on the page and I want it to call some javascript after the cswp renders?
    – Rothrock
    Sep 25, 2015 at 20:05
0

You can add line of code after including script,

ExecuteOrDelayUntilScriptLoaded( function() { <your custom function name>; }, 'name of   display template ');

for example:

ExecuteOrDelayUntilScriptLoaded( function() { console.dir( SP.Res ); }, 'sp.js');
1
  • This is not what i am asking Oct 29, 2012 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.