Best practice for using an external library on the window object

210 Views Asked by At

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.

1

There are 1 best solutions below

0
rabsom On

One way to do so is to wait for the library to be loaded before using it :

var src= "https://yourlibrarypath";
var useSSL = document.location.protocol === 'https:';
var d = document, e = d.createElement('script'), p = d.getElementsByTagName('head')[0];
e.type = 'text/javascript';  e.async = true;
e.src = (useSSL ? 'https:' : 'http:') + src;
p.insertBefore(e, p.firstChild);

e.onload = function() {
  //library has been loaded...
}