What is the best way to add a callback function once all components have rendered?

I need to run a callback function that attaches event handlers to links on the page. The callback will be used to add a speedbump for external links.

Links can appear across multiple components, what would be the best way to run the callback?

Do I need to override every component that can have a link to use onMount? Is there a global “all components rendered” event I can use?

Thanks!

Hi Marc,

In the Theme, there is a placeholder Javascript file called script/on-ready.js. You can create a local shadow of that file and add your code. The JS in that file is executed after the initial render of all components on the page. Hopefully that is sufficient for your use case!

Hi Thomas,

Thanks for the quick response! I tested out the on-ready and it seems as though the js is executing before components mount on the page. This is not expected behavior correct? Was the onReady option updated in a recent sdk maybe?

No, I don’t think that is the expected behavior. Which Theme version are you on?

"name": "answers-hitchhiker-theme",
  "version": "1.15.0",

This is the version from the package.json correct?

I tried this out on a small test site. I saw that the code in on-ready.js was executed after most, but not all, the components were mounted. Some components, such as DirectAnswer, were not yet mounted. There are some SDK components that won’t be mounted until certain, additional conditions are met. Returning to the DirectAnswer component, that won’t actually be mounted unless a search has been executed that returned a direct answer. This behavior may be what you’re experiencing?

If you’re not able to get what you need with on-ready.js, you could provide an onMount to the relevant components. Each component exposes an onMount hook that is fired after the component mounts. Inside the hook, you should have access to all the different aspects of the component. You can read a bit more about it here: GitHub - yext/answers-search-ui: Answers Javascript API Library for building Search experiences.. To provide an onMount hook for an individual component, you would need to override the relevant script partial.