user2896120 user2896120 - 4 months ago 17
jQuery Question

Replacing images with jQuery

I have a website that works with desktop, tablet, and mobile. With desktop, the images on my website are big. With tablets, those same images get resized. And again with mobile, those same images get resized again. I am using the same images that are loaded on to desktop for mobile. This is poor performance for mobile devices. What I want is to replace those images, and display thumbnails for those images instead.

NOTE: The images are retrieved from my database using a PHP for-loop.

What I could do:

jQuery:

$(document).ready(function() {
// run test on initial page load
checkSize();

// run test on resize of the window
$(window).resize(checkSize);
});

//Function to the css rule
function checkSize(){
if ($(".sampleClass").css("float") == "none" ){
// replaces images code here
}
}


CSS:

.sampleClass {float:left;}
@media only screen and (max-width: 800px){
.sampleClass {float:none;}
}


What I assume will happen with this code, is that the large images will be loaded and then the thumbnails will be loaded. Thus, creating a worse experience. How can I make it so that the images are automatically replaced with thumbnails on mobile, without loading the large desktop images?

Answer

Something like this?

<img src="loader.gif" data-large-src="large-img-1.jpg" data-mobile-src="mobile-img-1.jpg"/>
<img src="loader.gif" data-large-src="large-img-2.jpg" data-mobile-src="mobile-img-2.jpg"/>

function checkSize(){
    if ($(".sampleClass").css("float") == "none" ){
        // init all the images with small versions of images
        $('img').each(function() {
          $(this).attr('src', $(this).attr('data-mobile-src'));  
        });
    }
    else {
      // init all the images with large versions of images
      $('img').each(function() {
        $(this).attr('src', $(this).attr('data-large-src'));
      });
    }
}