Lazy Loading images within jQuery Mobile
jquery, jquery-mobile
Solution
The `window.load` function will fire only once, and you are binding to it after it fires when pages are pulled into the DOM via AJAX. The solution to your issue is pretty easy, run the code when the specific page initializes:
$(document).delegate('#about', 'pageinit', function() {
//notice I start the selection with the current page,
//this way you only run the code on images on this pseudo-page
$(this).find("img.lazy").lazyload();
});
This should work just fine since `pageinit` won't fire until after `document.ready` fires.
Also notice I used `.delegate()` instead of `.live()` since `.live()` has been depreciated and could be removed from future releases.
$(SELECTION).live(EVENT, EVENT-HANDLER);
is the same as:
$(document).delegate(SELECTION, EVENT, EVENT-HANDLER);
And for the bonus round, as of jQuery 1.7, both of the above functions actually map to `.on()` and you can use `.on()` in a delegated manor like so:
$(document).on(EVENT, SELECTION, EVENT-HANDLER);
Documentation:
- `.live()`: http://api.jquery.com/live
- `.delegate()`: http://api.jquery.com/delegate
- `.on()`: http://api.jquery.com/on
The reason your code worked on the first page-view was because the `window.load` event was firing after you bound to it in the `pageinit` event handler, but on subsequent AJAX loads you are binding to the `window.load` event even though it won't fire anymore.
Problem
I'm trying to implement the Lazy Load plugin into my jQueryMobile site to help speed up loadtimes on pages that contain a ton of images. If I bypass JQM's ajax page-loading by going directly to the URL like this: `http://hello.com/about`, the lazy loading works great. However, if I click-through to the About page from another page, which utilizes JQM's ajax page-loading, Lazy Load doesn't load. The About page has an id of `about` => `<div data-role="page" data-theme="a" id="about">` I've tried a number of variations of binding to the `pageinit` function with no success. My latest attempt is: ``` $('#about').live('pageinit', function() { $(window).load(function() { $("img.lazy").lazyload(); }); }); ``` Any guidance on this would be awesome. Thanks guys.