jQuery / PHP - Lazy loading gallery keeps trying to fetch images even when they've all loaded
I've got an image gallery that is showing one image per row inside of a div. I don't want the next image to load until it r开发者_如何转开发eaches the edge of the viewport (to save on server resources). All the images are named sequentially in the same folder (img/1.jpeg, img/2.jpeg, img/3.jpeg, ...).
I'm using a modified jQuery plugin to do this, but it still keeps trying to fetch the next image after all the images in the directory have been loaded. It's the last if statement I'm having trouble with here.
How do I stop the function from running once the last image in the directory has loaded?
<?php
// Count total number of images in the directory
$directory = "img/";
$totalImages = count(glob("" . $directory . "*.jpeg"));
?>
<script type="text/javascript">
$('document').ready(function(){
scrollalert();
});
function scrollalert(){
var scrolltop=$('#scrollbox').attr('scrollTop');
var scrollheight=$('#scrollbox').attr('scrollHeight');
var windowheight=$('#scrollbox').attr('clientHeight');
if(scrolltop>=(scrollheight-(windowheight)))
{
// Fetch next image
var nextImgNum=$('#content img').length + 1;
$('#content').append('<img src=\"book1/'+nextImgNum+'.jpeg\" /><br />');
updatestatus();
}
if(nextImgNum<=<?php echo $totalImages ?>)
{
setTimeout('scrollalert();', 0);
}
}
</script>
Any tips to optimize this script are greatly appreciated too :)
That script is highly inefficient and keeps the browser quite busy. You're basically in a tight loop checking whether the user has scrolled the page and avoiding the browser's script timeout via the use of setTimeout(). This is not something I would recommend. You can definitely fix this issue, but why not use the jQuery Lazy Load plug-in?
http://plugins.jquery.com/project/lazyload
Be careful with the lazyload plugin, it doesn't work properly with webkit.
See Bug 6656 (this bug may also be related to your problem) and the project page for Lazyload
Change your comparison operator from <= to <.
精彩评论