在Chrome中按顺序加载脚本 [英] Scripts loading out of order in Chrome
问题描述
我在< body>
底部有一个外部脚本,后面跟着一个内联脚本。它看起来像内联脚本运行在外部脚本之前,根据这个答案,这是不应该发生的。
I have an external script followed by an inline script at the bottom of my <body>
. It looks like the inline script is running before the external script, which isn't supposed to happen, according to this answer:
如果你不会动态加载脚本或将它们标记为延迟或
异步,则会按页面中遇到的顺序加载脚本。
无论它是外部脚本还是内联脚本
- 它们都按页面中遇到的顺序执行。
在外部脚本之后出现的内联脚本会一直保留,直到
加载并运行之前的所有外部脚本。 Src: https://stackoverflow.com/a/8996894/114855
Src: https://stackoverflow.com/a/8996894/114855
这是我的代码:
This is my code:
<script src="https://checkout.stripe.com/checkout.js"></script>
<script>
var handler = StripeCheckout.configure({
key: 'pk_live_HhFqemZFyEUJVorFzYvjUK2j',
token: function(res) {
$('#pay_token').val(res.id);
$('#pay_email').val(res.email)
$('#pay_amount').val(parseFloat($("#amount").val())*100);
$('#pay_description').val($("#description").val());
$('#pay_real').submit();
}
});
/* .. */
</script>
</body>
控制台显示StripeCheckout没有被定义(外部脚本应该定义)
Console is showing that StripeCheckout is not defined (which the external script should define)
这是有道理的,因为网络选项卡显示我的外部请求仍在等待处理。但我不确定为什么浏览器不会等待checkout.js被提取:
This makes sense, since the network tab shows that my external request is still pending. But I'm not sure why the browser didn't wait for checkout.js to be fetched:
推荐答案
Ahha - 我已经想通了!
Ahha - I've figured it out!
这是运行TurboLinks的Rails应用程序的一部分。
This is part of a rails application running TurboLinks.
TurboLinks动态更改主体内容,而不是每创建一个新请求当你点击一个链接。这意味着我的脚本标签被动态插入,并保证它们按顺序运行。
TurboLinks dynamically changes the body content instead of creating a new request every time you click a link. This means my script tags are being inserted dynamically, and the guarantee that they're run in order is lost.
由于TurboLinks不会在每次请求时重新评估脚本标记,我认为这里最简单/最好的解决方案是在我的应用程序的每个页面上包含StripeCheckout(不仅仅是需要的),在< head>
Since TurboLinks does not re-evaluate script tags on every request, I think the easiest/best solution here is to include StripeCheckout on every page of my app (not just the one's it's needed on), within the <head>
我也认为TurboLinks可以通过找到一种按顺序运行脚本的方法来解决这个问题。我打算跟进他们的github上的问题,并会相应地进行更新。
I also think TurboLinks can resolve this by finding a way to run the scripts in order. I plan to followup with an issue on their github, and will update here accordingly.
这篇关于在Chrome中按顺序加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!