
本文详解 window.onload 失效的根本原因——异步资源加载时机冲突,并提供基于 async/await 的可靠解决方案,确保 DOM 就绪、数据加载完成、筛选逻辑按序执行。
本文详解 `window.onload` 失效的根本原因——异步资源加载时机冲突,并提供基于 `async/await` 的可靠解决方案,确保 dom 就绪、数据加载完成、筛选逻辑按序执行。
在 Web 开发中,window.onload 常被误认为“页面完全就绪”的万能钩子。但需明确:window.onload 仅保证 HTML 文档、样式表、脚本及所有依赖资源(如图片)加载完毕,并不等待异步操作(如 fetch())完成。这正是你遇到问题的核心原因。
你的原始代码中存在两个关键时序冲突:
- 全局调用 fetchProducts(); —— 在脚本解析阶段立即发起 JSON 请求,此时 DOM 可能尚未构建完成(尤其当 <script> 标签位于 <head> 中),导致 document.getElementById("products") 返回 null;</script>
- window.onload 仅执行 filterProduct("all") —— 但此时 displayProducts() 尚未运行(因 fetch 是异步的),#products 容器内仍为空,筛选自然无效。
✅ 正确做法是:将 fetchProducts() 的调用纳入 onload 生命周期,并确保其完成后再执行筛选。由于 fetchProducts() 是 async 函数,必须使用 await 等待其 Promise 解析。
以下是优化后的核心逻辑(含必要修正):
const productsJsonFile = '../products.json';
async function fetchProducts() {
try {
const response = await fetch(productsJsonFile);
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
const products = await response.json();
displayProducts(products);
} catch (error) {
console.error('❌ Failed to load products:', error);
// 可选:显示友好的错误提示 UI
document.getElementById("products")?.insertAdjacentHTML(
'beforeend',
'<div class="error">Failed to load product list. Please refresh.</div>'
);
}
}
function displayProducts(products) {
const productContainer = document.getElementById("products");
if (!productContainer) {
console.error('⚠️ #products element not found in DOM');
return;
}
products.forEach(product => {
const card = document.createElement("div");
card.className = `card ${product.category} hide`; // 合并 class 更简洁
const imgContainer = document.createElement("div");
imgContainer.className = "image-container";
const image = document.createElement("img");
image.src = product.image;
image.alt = product.name;
imgContainer.appendChild(image);
card.appendChild(imgContainer);
const container = document.createElement("div");
container.className = "container2";
const name = document.createElement("h5");
name.className = "product-name";
name.textContent = product.name.toUpperCase();
container.appendChild(name);
const rating = document.createElement("div");
rating.className = "rating";
for (let i = 1; i <= 5; i++) {
const starIcon = document.createElement("i");
starIcon.className = "fa";
if (i <= product.rating) {
starIcon.classList.add("fa-star");
} else if (Math.abs(i - 0.5 - product.rating) < 0.1) { // 避免浮点误差
starIcon.classList.add("fa-star-half-o");
} else {
starIcon.classList.add("fa-star-o");
}
rating.appendChild(starIcon);
}
container.appendChild(rating);
const price = document.createElement("h6");
price.className = "price";
price.textContent = `Php ${product.price}.00`;
container.appendChild(price);
card.appendChild(container);
productContainer.appendChild(card);
});
}
function filterProduct(value) {
// 激活按钮状态
document.querySelectorAll(".button-value").forEach(btn => {
btn.classList.toggle("active-cat", btn.textContent.trim().toUpperCase() === value.toUpperCase());
});
// 筛选卡片
document.querySelectorAll(".card").forEach(card => {
if (value === "all") {
card.classList.remove("hide");
} else {
card.classList.toggle("hide", !card.classList.contains(value));
}
});
}
// ✅ 关键修复:onload 中串行执行异步获取 + 同步筛选
window.onload = async () => {
await fetchProducts(); // 等待数据加载并渲染完成
filterProduct("all"); // 再执行初始筛选
};? 重要注意事项:
- 移除全局 fetchProducts(); 调用:原代码末尾的独立调用必须删除,否则会与 onload 中的调用竞争,造成重复请求或 DOM 访问错误。
- DOM 元素存在性校验:displayProducts() 中增加了 if (!productContainer) 检查,避免因 HTML 结构缺失导致脚本崩溃。
- 错误处理增强:fetch 后增加 response.ok 判断,捕获 HTTP 错误(如 404);JSON 解析失败也会被捕获。
- <script> 放置建议</script>:若将 <script> 标签置于 <body> 底部(紧邻 </script>










