Load loop images on click / defer image loading until click or other event

So instead of loading a loop on click, I loaded the loop as usual, but instead of loading the images, I retrieved their URL’s and collected them in a data attribute. Then, I have that handy in the loop already without actually loading the images (who’s weight was the real issue).

On click, or any event – I then give that stored string to the src attribute of the img

This got my page load from 14mb to 1.2mb.

HTML / PHP whatever

// start loop // WP_Query

<div class="slideshow-image"
    <img
    data-image-url="<?php echo wp_get_attachment_url(get_post_thumbnail_id()); ?>"
    src="https://wordpress.stackexchange.com/questions/142136/<?php bloginfo("template_directory'); ?>/images/blank.gif" 
    alt="slideshow image" />
</div>

// end loop

jQuery

// load slideshow image only after you click
$("#porthole-slideshow-link").on('click', function() {

  $('.slideshow-image img').each( function() {

    var imageUrl = $(this).attr("data-image-url");
    $(this).attr('src', imageUrl);

  });

});

more:

I put this idea into action on many more things not in the loop so I could load only the most important assets and then after DOM load, things like the social buttons (which are big in this case) after the site structure is all done.

HTML

<img
class="load-me-after-dom"
data-image-url="http://example.com/images/my-huge-image.png"
src="http://example.com/images/blank.gif"
alt="my description" />

jQuery

$('.load-me-after-dom').each( function() {
  var imageUrl = $(this).attr("data-image-url");
  $(this).attr('src', imageUrl);
});