This topic has been on my mind the last little while and I have been thinking about the efficiency for DOM updates relating to replacing / updating images. I haven’t been able to find a discussion on this specifically and I am not even sure if there is an ideal solution between the two options I’ll show below.
The best answer I’ve come up with is that is it totally dependent on if you need to update additional attributes on the <img> tag like the alt, width, height values if they are being used.
Ok, so say you want to update an image or do an image swap between two images, what do you believe is the most efficient or elegant way. Is it better to replace the <img> element completely with a new <img> element with an updated src or to only update the existing <img>‘s src value with the new image?
The example I have use small images, would performance be effected by image size or whatever.
The two ways I have are:
$('.swapimage_ele').on("click", function(evt){
var img1 = $("#img1").html();
var img2 = $("#img2").html();
$("#img1").html(img2);
$("#img2").html(img1);
});
$('.swapimage_src').on("click", function(evt){
var img1 = $("#img1 img").attr("src");
var img2 = $("#img2 img").attr("src");
$("#img1 img").attr("src", img2);
$("#img2 img").attr("src", img1);
});
The quick working example I’ve wrote showing the two options is here: http://jsfiddle.net/jshaw/KMmeR/
Just curious on everyone’s opinion or preference and if there’s an ideal way of doing this.
Less jQuery, and definitely not using
.html()Or if you must support IE6/7: