javascript - 第二次追加时停止图像加载

标签 javascript php jquery caching

我正在开发一个聊天应用程序,它会附加如下数据

   $(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/

相关文章:

javascript - 使用源数据属性自动完成?

javascript - 如何从本地网络(LAN)外部访问node.js?

javascript - 如何解决 DOM hierarchy,Uncaught DOMException : Failed to execute '$x'

php - jQuery Datatables.net 库 - 将撇号插入 MySQL

php - 发布http ://localhost:8000/index/bots 500 (Internal Server Error)

javascript - 我如何在 Highchart 中使列和 y 轴之间有 1px 的空间?

javascript - 我怎样才能隐藏我的 html 源代码不被复制?

javascript - 对象字面量和方法分组

javascript - 添加指向 CSS :nth-child class 的链接

php - 为什么我不应该在PHP中使用mysql_ *函数?