Running JS only after all Display Templates have loaded

Something that we hit on the a project I have been working on recently, when I have been asked about by a colleague is how to only run some JS scripts, after one or more display template(s) have run. Well the answer is, you can do that quite easily if you only need to wait for one display template to load…

First off, update your display template and put the following in after it finishes rendering:

Now that this is in place you can wrap the code you don’t want to run with the following:

What If there are more than one?

Now, this is where it gets tricky. When you need to ensure that two or more display templates have loaded and rendered on a given page, you need to be a bit more creative with ‘Promises or Subscriptions’.

So the process is you would need to setup a SubscriptionEvent widget/extension in jQuery like explained in the post and then run the publish event in each of your display templates…

Now that you have done this, each time one of these display templates invokes, it will call any subscribing code. So we obviously need to setup this subscribing code and wrap the JS you need to run after the desired count of display templates have loaded, like in the following example…

Just make sure that the $.SubscriptionEvent code is readily available before the display templates or wrapped code (see above) is called. Simples.

Running JS only after all Display Templates have loaded

One thought on “Running JS only after all Display Templates have loaded

Leave a Reply

%d bloggers like this: