0

I am using srcset for responsive images on my site:

<img src="images/house-1915.jpg"
    srcset="images/house-544.jpg 544w, images/house-768.jpg 768w, images/house-992.jpg 992w, images/house-1200.jpg 1200w, images/house-1915.jpg 1915w"
    alt="House" class="hero-image">

I don't particularly like how it renders images. For example, when i'm on a screen with a 400px width, the 768w image is displayed. I wrote the following code in order to handle manual resizing:

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

function changeSrcset() {
  var windowWidth = $(window).width();

  if (windowWidth <= 544) {
    $('.hero-image').attr('srcset', '/static/images/house-544.jpg');
  } else if (windowWidth <= 768) {
    $('.hero-image').attr('srcset', '/static/images/house-768.jpg');
  } else if (windowWidth <= 992) {
    $('.hero-image').attr('srcset', '/static/images/house-992.jpg');
  } else if (windowWidth <= 1200) {
    $('.hero-image').attr('srcset', '/static/images/house-1200.jpg');
  } else {
    $('.hero-image').attr('srcset', '/static/images/house-1915.jpg');
  }

  $('.hero-image').css('width', windowWidth);
}

I am curious if removing srcset and using the above code to set the img src on page load is efficient?

Molly Harper
  • 2,363
  • 3
  • 26
  • 35
  • Have you tried using the [`sizes` attribute together with `srcset`](https://developer.mozilla.org/en-US/Learn/HTML/Multimedia_and_embedding/Responsive_images#Resolution_switching_Different_sizes)? – nnnnnn Aug 21 '16 at 01:08
  • @nnnnnn I did, but maybe I don't understand it well enough. – Molly Harper Aug 21 '16 at 01:11
  • I've never actually used it in a project, but the article I linked to seemed to explain it pretty well. – nnnnnn Aug 21 '16 at 01:17
  • @nnnnnn That article is really helpful, thank you!! I have always viewed width and pixels as the same. Do you understand the difference? – Molly Harper Aug 21 '16 at 01:43
  • A source image does have a certain number of pixels, but different devices have different DPI. So on three different phones with four-inch screens the same image could look different widths if no compensation is made for DPI. – nnnnnn Aug 21 '16 at 02:02

0 Answers0