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

时间:2019-03-23 15:24:52

标签: javascript stripe-payments lazy-loading

我将以下代码作为脚本的一部分,该脚本打开了带区检出功能。麻烦的是,没有多少人会使用它,而stripe正在减慢我的网站的速度,它在每个页面上的加载量都超过280kb,并发出40个http请求。我只想当某人单击“购买”时才加载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>$10</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。

1 个答案:

答案 0 :(得分:1)

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