lundi 30 janvier 2017

Javascript thundering herd loading external library from CDN

The first time pica() is used, it will load the external library. However, if pica() is used a second time before it finishes loading the external JS, it should not load the library a second time so alert() will run.

let picaStatus = 0;

function pica(...args) {
  if (picaStatus == 1) { // library previously loaded
    pica.resizeCanvas(...args);
  } else if (picaStatus == 0) { // library hasn't been loaded
    picaStatus = -1;
    $.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js", () => {
      picaStatus = 1;
      pica.resizeCanvas(...args);
    });
  } else if (picaStatus == -1) { // library is currently being loaded by another call
    alert('loading collision');
  }
}

Instead of throwing an alert() and dropping the function call, how can I make the second function call wait until the library is loaded?

Aucun commentaire:

Enregistrer un commentaire