Dopracowanie leniwego doładowywania stron (problemy są w momencie, kiedy skan strony...
[redakcja.git] / project / static / js / jquery.lazyload.js
1 (function($) {
2     jQuery.fn.lazyload = function(pattern, options) {
3         var settings = {
4             threshold: 0,
5             scrollThreshold: 300,
6             placeholder: 'loading...',
7             checkInterval: 2000
8         };
9         
10         if (options) {
11             $.extend(settings, options);
12         }
13         
14         var container = this;
15         container.data('lastScroll', -10000);
16         
17         function aboveViewport(container, element, threshold) {
18             return $(container).offset().top >= $(element).offset().top + $(element).height() + threshold;
19         }
20         
21         function belowViewport(container, element, threshold) {
22             return $(container).offset().top + $(container).height() + threshold <= $(element).offset().top;
23         }
24         
25         function checkScroll() {
26             if (Math.abs(container.scrollTop() - container.data('lastScroll')) > settings.scrollThreshold) {
27                 container.data('lastScroll', container.scrollTop());
28                 
29                 $(pattern, container).each(function() {
30                     if (aboveViewport(container, this, settings.threshold)
31                         || belowViewport(container, this, settings.threshold)) {
32                         $(this).html(settings.placeholder);
33                     } else {
34                         $(this).html('');
35                         var self = this;
36                         $('<img src="' + $(this).attr('src') + '" width="' + $(this).width() + '" />').load(function() {
37                             if ($(this).height() > $(self).height()) {
38                                 $(self).height($(this).height());
39                             }
40                         }).appendTo(this);
41                     }
42                 })
43             }
44             setTimeout(checkScroll, settings.checkInterval);
45         }
46         
47         checkScroll();
48     };
49 })(jQuery);