1

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?

Winter
  • 2,407
  • 1
  • 19
  • 28

1 Answers1

0

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Thank you, that was the answer I was looking for. But how would I do it with css? – Winter Sep 15 '16 at 13:17
  • Because I don't want both of the images to load in mobile, even if they are hidden they will be loaded by the browser - as far as I know. – Winter Sep 15 '16 at 13:20
  • http://stackoverflow.com/questions/12158540/does-displaynone-prevent-an-image-from-loading – Winter Sep 15 '16 at 13:24