我正在开发一个聊天应用程序,它会附加如下数据
$(selector).append("<img src='image.php?id=username'><div id ='msg'>hi</div>");
因此,每次附加相同的图像时,都会一次又一次地请求图像 URL。
如何在追加时停止图像刷新,如果图像网址已加载,我希望它加载该图像缓存。
最佳答案
您可以克隆已经存在的元素。这样,所有数据和图像数据都会被保留,不需要重新获取。此外,此方法比通过字符串添加新 HTML 快数亿倍。
function startthefun() {
var imgElem = document.createElement('img');
imgElem.setAttribute('src','http://cdn.sstatic.net/stackoverflow/img/sprites.svg?v=1bc6a0c03b68');
document.getElementById('content').appendChild(imgElem);
window.timer = window.setInterval(function() {document.body.appendChild(imgElem.cloneNode());},1000);
}
<input type="button" value="start" onclick="startthefun()"><input type="button" onclick="window.clearInterval(window.timer)" value="stahp"><div id="content"></div>
您只需将 HTMLElement 输入到 $(selector).append(HTMLElement)
Jquery 会将 html 节点附加到您所选的项目。
关于javascript - 第二次追加时停止图像加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29213837/