Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load html, then load images using Ajax in Jquery

Basically what I'm looking for is performance here.

$.post(link,     
  function(data){
         //removes the image that was displayed while loading
         $("#loadingImg").remove();

         //append the new content, into the content div
         //and add a div around the new content in order to lazy load
         $("#content").append('<div id="new-page">' + data + '</div>');
         //lazy load the images inside the new div
         $("#new-page").find("img").lazyload({ 
                 placeholder : "/images/white.png", effect : "fadeIn" });
  });

I want to use the jquery plugin, lazy load, to lazy load images that are appended to some content. Right now I can tell that the loading time with and without the lazyload line of that code is exactly the same (it's loading about 20 images). I'm now assuming that the $("#content").append() line waits for all the images to load before appending.

Is there any way to put the html in the page, halt the browser from loading the images in that html, and then load them as the user scrolls?

By the way, even when I do:

data = '<div id="new-page-' + pageCounter + '">' + data + '</div>';
var newData = $(data);
newData.find("img").lazyload({ placeholder : "/images/white.png", effect : "fadeIn" });
$("#content").append(newData);

It still takes the same amount of time to load...

Thanks for the help!

like image 471
David Sherret Avatar asked Dec 21 '22 13:12

David Sherret


1 Answers

Is there any way to put the html in the page, halt the browser from loading the images in that html, and then load them as the user scrolls?

Yes there, is: jQuery waypoints: http://imakewebthings.github.com/jquery-waypoints/

Working example:

http://jsfiddle.net/marcosfromero/BbA9M/

HTML:

<img id="first" src="" width="364" height="126" deferred="http://www.google.com/images/logos/ps_logo2.png" />

<div style="height: 500px; ">Some vertical space. Scroll to the bottom</div>

<img id="second" src="" width="364" height="126" deferred="http://www.google.com/images/logos/ps_logo2.png" />

The only drawback that I find in this HTML code is that the deferred attribute is non standard.

jQuery:

$('img').waypoint(function(event, direction) {
    // set the image src attribute from the deferred one, which has the real URL
    this.src = this.getAttribute('deferred');
}, {
    triggerOnce: true, // load the image just once
    offset: function() {
        // calculate where the event should be fired
        // in this case, when the whole image is visible
        return $.waypoints('viewportHeight') - $(this).height();
        // if you want to load the image when the top of it is visible change it for
        // return $.waypoints('viewportHeight');
    }
})
like image 154
marcosfromero Avatar answered Jan 06 '23 22:01

marcosfromero