Winter Winter - 2 months ago 9
Javascript Question

will image load on every resize?

I have an image-tag in which I want to display different images in desktop and mobile.

I have solved it like this:

JS:

function displayResponsiveImage() {
var largeImage = $('.responsive-image img.desktop');
var smallImage = $('.responsive-image img.mobile');
var realImage = $('.responsive-image img.real');

var largeImageSrc = largeImage.data('imagesrc');
var smallImageSrc = smallImage.data('imagesrc');

var viewportWidth = window.innerWidth;

if (viewportWidth > 480) {
realImage.attr('src', largeImageSrc);
} else {
realImage.attr('src', smallImageSrc);
}

realImage.show();
largeImage.hide();
smallImage.hide();
};

$(window).on('resize', function () {
displayResponsiveImage();
});


HTML:

<div class="image-container responsive-image" style="">
<a href="@Url.ContentUrl(Model.Link)">
<img class="desktop" data-imagesrc="@Html.GetUrl(Model.Image, true)" />
<img class="mobile" data-imagesrc="@Html.GetUrl(Model.MobileImage, true)" />
<img class="real" title="@Model.AltText" alt="@Model.AltText" />
</a>
</div>


My question is: with this set-up, will the image reload on every resize or will it only reload when the image changes src? In other words, do I need to optimize this further?

Answer

First off, if you are setting the .src property to the same value that it's already at, nothing will change, nothing will reload.

Secondly, images are cached by the browser so once they are loaded, any subsequent time they are used, they will be simply loaded from the cache which is fast.

FYI, you could probably do all this with CSS media queries and let the browser handle it automatically.