'Get callback inside Angular when external script add element

I'm integrating external library into Angular App. It's a Trust Shop badge, process can be traced over here

Just for referece, integration code that needs to be pasted into app's index.html looks following:

<script type="text/javascript">
  (function () {
    var _tsid = 'Your-secret-is';
    _tsConfig = {
      /* Just set of config stuff */
    };
    var _ts = document.createElement('script');
    _ts.type = 'text/javascript';
    _ts.charset = 'utf-8';
    _ts.async = true;
    _ts.src = '//widgets.trustedshops.com/js/' + _tsid + '.js';
    var __ts = document.getElementsByTagName('script')[0];
    __ts.parentNode.insertBefore(_ts, __ts);
  })();
</script>

Due to some requirements to show/hide badge on different segments of page I'm forced to perform some programmatic style and class attributes manipulation of floating Trust Badge div element.

Unfortunately, this div is embedded into DOM asynchronously, after probably some under-the-hood rating fetching by this script. Im unable to catch it both in window.load callback and in Angular itself onInint, afterViewInit. And even if, those methods would be rather based on pure luck than on some systematyce approach.

For now, only reliable way of fetching this element as soon as possible was basically hooking in come periodic checks in AppModule:

export class AppModule {
  const intId = setInterval(() => {
    if (this.appService.setTrustBadgeClass()) {
        clearInterval(intId);
    }
  }, 500);
}

and service itself:

    public setTrustBadgeClass(): boolean {
        const element = this.document.querySelector<HTMLElement>("[id^='minimized-trustbadge-']");
        if (element) {
            this.trustBageClassList = element.className;
            this.trustBadgeFullId = element.id;
            return true;
        } else {
            return false;
        }
    }

It works, but it's kinda ugly. Maybe some of you have better idea, how I can efficiently and reliable get this element? I can besically inject whole window object into initialization script to notify Angular guts on progres.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source