Winter Winter - 1 year ago 74
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:


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

var largeImageSrc ='imagesrc');
var smallImageSrc ='imagesrc');

var viewportWidth = window.innerWidth;

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

$(window).on('resize', function () {


<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" />

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download