Friday, January 22, 2016

Do something after all refiners templates have completed rendering

image
Elio Struyf is a good friend and did a post today which I have shamelessly copied my post title from. Elio missed an approach on how to run code once all refiners (or other search part) has been rendered, so I figured I’d help him out :-)

Be sure to read Elio’s excellent post before you continue!
Recently I’ve been working on a solution which is POC complete on how to inject custom query variables client side (better synonyms for example) which has made me dig into the object structure of a page with search web parts on it. I used some on this for my Lightweight search center posts as well.

All pages using search web parts have a script manager present which controls the search web parts as well as the data providers per web part. Here’s how you get a handle to it:

var manager = Srch.ScriptApplicationManager.get_current();

Next up each search web is hooked to a query group. For a search page you have one named Default, and for a page with multiple CSWP’s you have one per webpart randomly named unless you name them in the .webpart config (by fellow Pzl’er Petter Skodvin-Hvammen). Each web part tied to a query group is listed in the displays property of the query group. For a search page with results and refiners you would have two web parts listed.

var defaultQueryGroup = manager.queryGroups["Default"];
var searchControls = defaultQueryGroup.displays;

image

From the image above you see two objects. One for the refinement web part and one for the main search results. Next up is knowing how the object and event model works. Each webpart has an event named results rendered which you can hook into. To add a function to be called for the refiner you can use the following code:

for (var i = 0; i < searchControls.length; i++) {
    if (searchControls[i] instanceof Srch.Refinement) {
        searchControls[i].add_resultRendered( function (sender, e) {            
            // something;
            console.log('Rendering is complete and DOM available');
        });
        break;
    }
}

Download

You can download the complete script from my github repo https://github.com/wobba/Scripts/blob/master/mAdcOW.Search.resultRendered.js where it also shows how you can use the sender/e variables returned on the callback.

Summary

As always, there is at least three ways to accomplish a single task in SharePoint :-)

2 comments:

  1. Hi, in your github script, you should have the block
    ExecuteOrDelayUntilBodyLoaded(function () {
    Sys.Application.add_init(hookScript);
    });
    out of your actual hookscript function!

    Thanks!

    ReplyDelete
    Replies
    1. Thanks...and are you reviewing all my code ;) Fixed the repo.

      Delete