In my code I rely on an external library which I expect to be loaded on the window object on the pages where my snippet is going to be running. My code looks like the following:
if (window.ats) {
window.ats.retrieveEnvelope(function (envelope: string) {
console.log('Located ATS.js');
this.cachedEnvelope = JSON.parse(envelope).envelope;
});
}
ats is the name of the library which I depend on. Locally this failed since ats is not one of the usual window properties. In order to make it compile and also be able to mock it in my tests, I created the following override:
declare global {
interface Window {
ats?: any;
}
}
I am wondering if this is the standard way to go about a situation like this. This (1) does make the code compile (2) should be able to allow the code identify the ats on a production environment and (3) allow mocking in the specs.
I am not a Javascript expert and I'd like to know if there's a better/standard way to address the aforementioned situation.
One way to do so is to wait for the library to be loaded before using it :