我如何将嵌入式javascript从html组件移动到单独的js文件,以便可以将其捆绑和缩小?
我正在编辑BigCommerce和最新的Cornerstone主题。
该组件是一个按钮,通过向店面api发出POST请求,将3个商品添加到购物车(它可以按预期工作,我只需要适当地移动它即可将其捆绑在一起)
<script>
let lineItems = {
"lineItems": [
{
"quantity": 1,
"productId": 103
},
{
"quantity": 1,
"productId": 81
},
{
"quantity": 1,
"productId": 77,
"variantId": 11
}
]
};
function postData(url = ``, cartItems = {}) {
return fetch(url, {
method: "POST",
credentials: "same-origin",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(cartItems),
}).then(function (response) {
redirectToCart();
});
}
function redirectToCart() {
window.location = "/cart.php";
}
function showLoadingOverlay() {
document.getElementsByClassName("loadingOverlay").forEach(x => x.style.display = "block");
}
function addBundleToCart() {
let cartID = "{{cart_id}}"
let url = `/api/storefront/cart`;
if (cartID.length > 0) {
// cart wasn't empty, update url
showLoadingOverlay();
url = `/api/storefront/carts/${cartID}/items`
}
postData(url, lineItems)
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
}
</script>
<button type="button" style="margin:0 auto;display:table; padding:20px; font-size: 1.5em; font-weight: bold; border: 3px solid rgba(128, 128, 128, 0.164)"
onclick="addBundleToCart()" id="addToCart">ADD BUNDLE TO CART</button>
我正在阅读文档,目前尚不清楚该怎么做。我是否应该为此创建一个自定义模板?(品牌,类别,页面,产品)
[如果有必要将其添加到捆绑的主题中,则可以将.js文件添加到资产文件夹,并在使用该按钮的HTML文件中引用该脚本。 I recommend taking a look at the Handlebars Helpers for injection found here,提供有关使用CDN高效引用脚本的详细信息。