脚本标签未在 Shopify 应用嵌入块内执行

问题描述 投票:0回答:1

我正在开发一个Shopify 应用程序嵌入块来显示推荐产品列表。 H1标签(“推荐商品”)成功显示在页面上,但由于

<script>
标签内的JavaScript代码未执行,因此未渲染商品列表。这是我的代码:

<div id="custom-product-list" class="product-list">
  <!-- Products will be injected here by JavaScript -->
  <h1>Recommended Products</h1>
</div>

<script>
  // Mock products array (this can be fetched via AJAX instead)
  export const products = [
    {
      _id: '1',
      title: 'product 1',
      description: 'Lorem ipsum product 1 dummy description.',
      price: 100,
      compare_at_price: 80,
      featured_image: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
      url: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
    },
    {
      _id: '2',
      title: 'product 2',
      description: 'Lorem ipsum product 2 dummy description.',
      price: 200,
      featured_image: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
      url: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
    }
  ];

  function renderProducts(productList) {
    const productContainer = document.getElementById('custom-product-list');
    productContainer.innerHTML = '';

    productList.forEach((product) => {
      const productItem = `
        <div class="product-item">
          <a href="${product.url}">
            <img src="${product.featured_image}" alt="${product.title}">
          </a>
          <h3><a href="${product.url}">${product.title}</a></h3>
          <p class="price">
            ${product.compare_at_price > product.price
              ? `<span class="sale-price">$${product.price}</span>
                 <span class="original-price">$${product.compare_at_price}</span>`
              : `<span class="regular-price">$${product.price}</span>`}
          </p>
        </div>
      `;
      productContainer.insertAdjacentHTML('beforeend', productItem);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);
  });
</script>

{% schema %}
{
  "name": "Custom Product List",
  "target": "section",
  "settings": [
    {
      "type": "number",
      "id": "product_limit",
      "label": "Number of Products",
      "default": 5
    }
  ]
}
{% endschema %}

页面上出现H1标签,但负责渲染产品的脚本没有运行。此代码位于应用程序嵌入块的 Shopify Liquid 模板文件内。

为什么 JavaScript 在此 Shopify 应用嵌入块中未执行,如何确保执行脚本以显示产品列表?

javascript shopify liquid shopify-app shopify-app-extension
1个回答
0
投票

尝试以下操作。 也许这是

DOMContentLoaded
在脚本之前触发的问题。

更换:

document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);
  });
if (document.readyState === "loading") {
    // Loading hasn't finished yet
    document.addEventListener("DOMContentLoaded", () => {
        renderProducts(products);
    });
} else {
    // `DOMContentLoaded` has already fired
    renderProducts(products);
}

来源: https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event

© www.soinside.com 2019 - 2024. All rights reserved.