jQuery Change Image src attribute is too slow -
i calculate command takes 90ms change image src.
$('#tab3 #' + arrsong[i].songid + ' .sogselect button#select-'+arrsong[i].songid+' img').attr('src', 'images/icon_add_active.png');
changing 1 or 2 image, don't see latency when in loop many commands costs time.
is there anyway better?
first, add class name image. shouldn't calculate such long dom selector every time access known object.
if need store value, use data
attribute.
<img class="sogselectimage" src="1.png" data-songid="1" />
now, can access using such query:
$(".sogselectimage[data-songid='" + arrsong[i].songid + "']").attr("src", "2.png");
it should work faster.
if in loop, can way:
$(".sogselectimage").each(function() { var songid = $(this).data('songid'); $(this).attr("src", "something_else.png"); });
or using for
loop way (which worse in terms of productivity):
var images = $(".sogselectimage"); (int = 0; < arrsong.length; i++) { images.find("[data-songid='" + arrsong[i].songid + "']").attr('src', '2.png'); }
also, if change same image img
s, don't 1 one. use classes.
// css .sogselectimage { background-image: url('1.png'); background-position: center center; background-size: cover; background-repeat: no-repeat; } .sogselectimage.sogselectimage-add { background-image: url('./images/icon_add_active.png'); } // js $(".sogselectimage").addclass("sogselectimage-add");
anyway, guess, problem calculate dom selector of 5 elements every time in loop. not good.
Comments
Post a Comment