第一次使用pica()时,它将加载外部库。但是,如果pica()在完成加载外部JS之前第二次使用,则不应再次加载该库,因此alert()将运行。

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');
  }
}


而不是抛出alert()并删除函数调用,我如何使第二个函数调用等待直到加载库?

最佳答案

使状态成为已加载脚本的承诺:

let picaStatus = null;

function pica(...args) {
  if (!picaStatus) { // library hasn't been loaded
    picaStatus = $.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js");
  }
  picaStatus.then(() => {
    pica.resizeCanvas(...args);
  });
}

关于javascript - 从CDN加载外部库的Javascript雷群,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41947983/

10-13 00:34