简体   繁体   中英

Stop Image load on append 2nd time

I am developing an chat application and it appends data like below

   $(selector).append("<img src='image.php?id=username'><div id ='msg'>hi</div>");

So each time when same image is appended , Its requesting the image URL again and again .

How to stop the image refresh on append , If the image url is already loaded, I want it to load that image cache.

You could clone the already existing Element. That way all data and image data is preserved and doesn't need to be fetched anew. Also this method is gazillion times faster than adding the new HTML via string.

 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> 

You can just simply feed the HTMLElement into the $(selector).append(HTMLElement) Jquery will append the html node to your selected item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM