Shopify App Embed Block内脚本未执行问题排查与解决
问题原因分析
你的JavaScript脚本在Shopify App Embed Block中无法执行,核心原因有两个:
- ES模块语法错误:普通
<script>标签不支持export关键字(这是ES模块专属语法),会直接触发语法错误导致脚本终止执行。 - 事件监听时机不匹配:
DOMContentLoaded事件在页面初始加载完成后就会触发,但Shopify App Embed Block属于动态加载内容,脚本执行时该事件可能已触发完毕,导致回调函数无法执行。
解决方案
针对上述问题,通过以下步骤修复:
- 移除
export关键字:将export const products改为const products,让脚本以普通模式执行,避免语法错误。 - 替换事件监听:使用Shopify专属的
shopify:section:load事件替代DOMContentLoaded,该事件会在Embed Block成功加载到页面时触发,确保脚本在正确时机执行。 - 保留原有标题:原代码会清空容器删除H1标签,修复后先保留标题再渲染商品列表。
- 添加元素存在性检查:避免因容器未加载导致的报错。
修改后的完整代码
<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) 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'); // 检查容器元素是否存在 if (!productContainer) return; // 保留H1标签,避免被清空 const heading = productContainer.querySelector('h1'); productContainer.innerHTML = ''; if (heading) productContainer.appendChild(heading); 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); }); } // 监听Shopify section加载事件 document.addEventListener('shopify:section:load', () => { renderProducts(products); }); // 兼容初始加载场景,直接执行一次 renderProducts(products); </script> {% schema %} { "name": "Custom Product List", "target": "section", "settings": [ { "type": "number", "id": "product_limit", "label": "Number of Products", "default": 5 } ] } {% endschema %}
内容的提问来源于stack exchange,提问作者Nirmal Sankalana
相关产品推荐
相关产品推荐

