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)?

This Guy
  • 83
  • 6
vikas mehta
  • 714
  • 3
  • 6
  • 15

2 Answers2

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(){});

Aaron
  • 732
  • 1
  • 9
  • 23
vikas mehta
  • 714
  • 3
  • 6
  • 15
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');
Anuja
  • 3,103
  • 4
  • 23
  • 27