使用Webpack构建项目:HTML与JS仅引入一张image.jpg却渲染两张的问题
Webpack项目中图片重复渲染问题解决
问题描述
用静态HTML、CSS、JS结合Webpack构建项目时,明明只在JS里引入了一张image.jpg,页面却渲染出两张相同图片。预期效果是图片仅显示一次,位于闪烁文本上方。
原代码
main.js
import imageSrc from './image.jpg'; // 按需调整路径 const imgElement = document.createElement('img'); imgElement.src = imageSrc; imgElement.alt = '图片描述'; document.body.appendChild(imgElement); const textElement = document.createElement('h1'); textElement.textContent = '这段文字会闪烁!'; document.body.appendChild(textElement); setInterval(() => { textElement.style.visibility = (textElement.style.visibility === 'hidden' ? '' : 'hidden'); }, 500);
main.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hello Webpack</title> <link rel="stylesheet" href="main.css"> </head> <body> <h1>Hello, World!</h1> <script src="main.js"></script> </body> </html>
解决方案
问题出在Webpack热模块更新时,旧的图片元素没被清理,每次代码变动都会新增一个图片元素。只需在创建新图片前,先移除页面中已存在的图片即可:
修改后的main.js
import imageSrc from './image.jpg'; // Webpack会自动处理资源路径 // 添加新图片前先移除已存在的图片元素 const existingImage = document.querySelector('img'); if (existingImage) { existingImage.remove(); } // 动态创建图片并添加到DOM const imgElement = document.createElement('img'); imgElement.src = imageSrc; // 指向Webpack处理后的图片URL imgElement.alt = '图片描述'; document.body.appendChild(imgElement); // 实现文本闪烁效果 const textElement = document.createElement('h1'); textElement.textContent = '这段文字会闪烁!'; document.body.appendChild(textElement); setInterval(() => { textElement.style.visibility = (textElement.style.visibility === 'hidden' ? '' : 'hidden'); }, 500);
内容的提问来源于stack exchange,提问作者neoraj.guardian
相关产品推荐
相关产品推荐

