延迟加载条带 - 导致未定义错误

Lazy Load Stripe - Results in undefined error

我将以下代码作为我的脚本的一部分,它可以打开条带结帐。问题是没有多少人会使用它,而且 stripe 正在减慢我的网站速度,它在每个页面上加载超过 280kb 并发出 40 个 http 请求。我只想在有人单击 "Buy" 时才加载 stripe.js。这是现有代码:

$button.addEventListener('click', () => {

  setTimeout(() => {
    $button.innerHTML = 'Waiting for response...';
  }, 500);

  handler.open({
    amount,
    name: 'Test Shop',
    description: 'A Fantastic New Widget'
  });
});

这是我最好的尝试 - 这次展示了完整的完整文件:

import uuid from 'uuid/v4';

const amount = 1000;
const $messageBox = document.getElementById('messageBox');
const $button = document.querySelector('button');

function resetButtonText() {
  $button.innerHTML = 'Click to Buy! <strong></strong>';
}

const handler = StripeCheckout.configure({
  key: STRIPE_PUBLISHABLE_KEY,
  image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
  locale: 'auto',
  closed: function () {
    resetButtonText();
  },
  token: function(token) {

    fetch(`${LAMBDA_ENDPOINT}purchase`, {
      method: 'POST',
      body: JSON.stringify({
        token,
        amount,
        idempotency_key: uuid()
      }),
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    })
    .then(res => res.json())
    .catch(error => console.error(error))
    .then(response => {

      resetButtonText();

      let message = typeof response === 'object' && response.status === 'succeeded'
        ? 'Charge was successful!'
        : 'Charge failed.'
      $messageBox.querySelector('h2').innerHTML = message;

      console.log(response);
    });
  }
});

$button.addEventListener('click', () => {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "https://checkout.stripe.com/checkout.js"; 
    document.getElementsByTagName("head")[0].appendChild(script);

  setTimeout(() => {
    $button.innerHTML = 'Waiting for response...';
  }, 500);

  handler.open({
    amount,
    name: 'Test Shop',
    description: 'A Fantastic New Widget'
  });
});

这会导致错误:

Uncaught ReferenceError: StripeCheckout is not defined
    at Module.<anonymous> 

如何避免这种情况?没有 jquery 请。

与其等待任意超时,不如将 script.onload 设置为回调函数并在那里进行设置。

$button.addEventListener('click', () => {
  $button.innerHTML = 'Waiting for response...';

  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://checkout.stripe.com/checkout.js";
  script.onload = function () {
    // Now that we have the script loaded, we can create the stripe handler...
    const handler = StripeCheckout.configure({
      key: STRIPE_PUBLISHABLE_KEY,
      image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
      locale: 'auto',
      closed: function () {
        resetButtonText();
      },
      token: function(token) {

        fetch(`${LAMBDA_ENDPOINT}purchase`, {
          method: 'POST',
          body: JSON.stringify({
            token,
            amount,
            idempotency_key: uuid()
          }),
          headers: new Headers({
            'Content-Type': 'application/json'
          })
        })
        .then(res => res.json())
        .catch(error => console.error(error))
        .then(response => {

          resetButtonText();

          let message = typeof response === 'object' && response.status === 'succeeded'
          ? 'Charge was successful!'
          : 'Charge failed.'
          $messageBox.querySelector('h2').innerHTML = message;

          console.log(response);
        });
      }
    });

    // and use the handler to do whatever we want.
    handler.open({
      amount,
      name: 'Test Shop',
      description: 'A Fantastic New Widget'
    });
  };
  document.getElementsByTagName("head")[0].appendChild(script);
});