Loading Images on-demand (or; disable loading of hidden images)

2.6k views Asked by At

I have a slider-like widget which is basically, a div of sub-divs containing some page content (together with images).

Initially, all sub-divs are hidden except the main one.

My problem is that all web browser seem to load (request) all images in the content, whether they're hidden or not.

In my case specifically, it will end up loading some 350 images at one go. This is a lot, especially when considering images are at the very least 200kb. In fact, the network log specifies that the total website size is in the range of 6mb to 7mb.

All these images hinder page load, especially because they are expected to load before other page elements (eg; buttons etc).

What is the solution to my problem? Things I tried already:

  • loading each sub-div as ajax. This is not possible, the page content must be there at all time.
  • hiding the images themselves (in the hope that the web browser does not load them). This failed, the browser still loaded images with CSS display:none;.
  • Possible solution: intentionally break the markup (server-side) so that the browser does not load the images, eg; writing <img alt="abc.jpg" src="about:blank"/>, then when tab switches, I would fix the markup correctly with jQuery. I haven't tried this yet, is it advisable?
1

There are 1 answers

0
Christian On BEST ANSWER

Well, as I hinted in the question, a possible solution can be achieved by the following trick:

<?php
    // server-side content
    echo str_replace(' src=', ' data-dly="" src="blank.gif" data-src="', $html);
?>

// client-side script
function showPage(id){
    hidePages();

    var page = jQuery('#page'+id);

    page.find('img[data-dly="1"]').each(function(){
        jQuery(this).attr('src',jQuery(this).attr('data-src'));
    }).removeAttr('data-dly').removeAttr('data-src');

    page.fadeIn();
}

NB: Thanks to @jeffreydev for the help as well.