Code Monkey home page Code Monkey logo

jquery.lazy's Introduction

jQuery & Zepto Lazy - Delayed Content, Image and Background Loader

GitHub version NPM version Bower version Dependencies Status devDependencies Status


JetBrains & PhpStorm
This project is friendly supported by JetBrains & PhpStorm!


Table of Contents


About Lazy

Lazy is a fast, feature-rich and lightweight delayed content loading plugin for jQuery and Zepto. It's designed to speed up page loading times and decrease traffic to your users by only loading the content in view. You can use Lazy in all vertical and horizontal scroll ways. It supports images in <img /> tags and backgrounds, supplied with css like background-image, by default. On those elements Lazy can set an default image or a placeholder while loading and supports retina displays as well. But Lazy is even able to load any other content you want by plugins and custom loaders.

Compatibility

Lazy will work with a wide range of browsers and support jQuery versions for years backwards and Zepto as alternative. You can pick any version since jQuery 1.7.2 or Zepto 1.1.6 or greater. There is no way to guarantee, that Lazy will work with all browsers, but all I've tested worked great so far. If you find any problems in specific browsers, please let me know.

Tested in: IE, Chrome (+ mobile), Firefox (+ mobile), Safari (+ mobile) and Android Browser.

Documentation / Examples

For documentation, examples and other information take a look on the project page.

Installation

First of all, you will need a copy of jQuery or Zepto to use Lazy successfully on your project. If you get this you can install Lazy by different ways. Some examples below:

CDN

Lazy and all plugins are available over cdnjs and jsDelivr CDN and can directly included to every page.

<!-- jsDeliver -->
<script type="text/javascript" src="//cdn.jsdelivr.net/gh/dkern/[email protected]/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/gh/dkern/[email protected]/jquery.lazy.plugins.min.js"></script>

<!-- cdnjs -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.10/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.10/jquery.lazy.plugins.min.js"></script>

Self-Hosted

Download and save one of two available files to include Lazy to your page, either the development or the minified version.

<script type="text/javascript" src="jquery.lazy.min.js"></script>

Package Managers

Lazy is even available through NPM and Bower. Just use one of the following commands below:

NPM

$ npm install jquery-lazy
$ bower install jquery-lazy

Basic Usage

1.) The basic usage of Lazy is pretty easy. First of all you need to prepare all elements you want to lazy load. By default add a data-src attribute to images containing the loadable image and/or a data-loader attribute to elements witch shall use a plugin or custom loaders.

<img class="lazy" data-src="path/to/image_to_load.jpg" src="" />

2.) Start using Lazy by calling it after page load. You don't have to specify your elements exactly, but for better performance, or different options, load your elements over unique classes or any other selector.

$(function($) {
    $("img.lazy").Lazy();
});

Take a look at the documentation to get an idea what Lazy is capable of.

Callbacks / Events

Lazy comes with a bunch of callbacks and events you can assign to. Just add them by initialization settings:

  • beforeLoad - before item is about to be loaded
  • afterLoad - after the item was loaded successfully
  • onError - whenever an item could not be loaded
  • onFinishedAll - after all items in instance was loaded or returned an error

Instances and public Functions

Lazy supports multiple parallel instances. Just initialize them with different selectors. To access an instances public functions you can initialize them in an object oriented manner or grab the instance bind to every element by default:

// object oriented way
var instance = $("img.lazy").Lazy({chainable: false});

// grab from elements (only works well if you use same selectors)
$("img.lazy").Lazy();
var instance = $("img.lazy").data("plugin_lazy");

Every instance has some public available functions to control it's behavior. There are currently six available:

instance.config(entryName[, newValue]); // get or set an configuration entry
instance.addItems(items); // add new items to current instance
instance.getItems(); // get all unhandled items left of current instance
instance.update([useThrottle]); // loads all elements in current viewport
instance.force(items); // force loading specific items, ignoring the viewport
instance.loadAll(); // loads all remaining available elements from this instance
instance.destroy(); // unbinds all events and stop execution directly

Custom Content Loaders

With the custom loaders option there is a powerful solution to load every contents the Lazy way. Lazy will handle everything, you just create a loading method witch got triggered whenever the element hits the visibility threshold. It is still possible to load images and custom loaders in the same Lazy instance.

To use this just define a loader function inside the Lazy initialisation and pass the loader name to the data-loader attribute of the elements witch should be lazy loaded.

<div class="lazy" data-loader="customLoaderName"></div>
<img class="lazy" data-src="path/to/image_to_load.jpg" src="" />
<div class="lazy" data-loader="customLoaderName"></div>
<div class="lazy" data-loader="asyncLoader"></div>
$(".lazy").Lazy({
    // callback
    beforeLoad: function(element) {
        console.log("start loading " + element.prop("tagName"));
    },

    // custom loaders
    customLoaderName: function(element) {
        element.html("element handled by custom loader");
        element.load();
    },
    asyncLoader: function(element, response) {
        setTimeout(function() {
            element.html("element handled by async loader");
            response(true);
        }, 1000);
    }
});

Loader Plugins

The loader plugins can extend the functionality of Lazy, like loading other elements and data. It is basically the same as the custom content loaders, with the difference, that plugins can extend all further instances globally at once permanently and let them handle specific elements like <video> by default, without data-loader attribute set. With custom content loaders you have to initialize each instance on setup with the loader. With plugins you only load the plugin file and you're done for all instances from now on.

For more information and examples, take a look at the existing plugins or the readme.md in there.

Configuration Parameters

The following configurations is available by default:

Name Type Default Description
name string 'lazy' Internal name, used for namespaces and bindings.
chainable boolean true By default Lazy is chainable and will return all elements. If set to false Lazy will return the created plugin instance itself for further use.
autoDestroy boolean true Will automatically destroy the instance when no further elements are available to handle.
bind string 'load' If set to load' Lazy starts working directly after page load. If you want to use Lazy on own events set it to event'.
threshold integer 500 Amount of pixels below the viewport, in which all images gets loaded before the user sees them.
visibleOnly boolean false Determine if only visible elements should be load.
appendScroll integer window An element to listen on for scroll events, useful when images are stored in a container.
scrollDirection string 'both' Determines the handles scroll direction. Possible values are both, vertical and horizontal.
imageBase string null If defined this will be used as base path for all images loaded by this instance.
defaultImage string blank image Base64 image string, set as default image source for every image without a predefined source attribute.
placeholder string null Base64 image string, set a background on every element as loading placeholder.
delay integer -1 If you want to load all elements at once after page load, then you can specify a delay time in milliseconds.
combined boolean false With this parameter, Lazy will combine the event driven and delayed element loading.
attributes
attribute string 'data-src' Name of the image tag src attribute, where the image path is stored.
srcsetAttribute string 'data-srcset' Name of the image tag srcset attribute, where the source set is stored.
sizesAttribute string 'data-sizes' Name of the image tag sizes attribute, where the size definition for source set is stored.
retinaAttribute string 'data-retina' Name of the image tag attribute, where the path for optional retina image is stored.
loaderAttribute string 'data-loader' Name or the element attribute, where the identifier of the plugin or customer loader is sored.
imageBaseAttribute string 'data-imagebase' Name ot the image tag element, where the specific image base is stored. This will overwrite the global imageBase config.
removeAttribute boolean true Determine if the attribute should be removed from the element after loading.
handledName string 'handled' Name of the element tag data attribute, to determine if element is already handled.
loadedName string 'loaded' Name of the element tag data attribute, to determine if element is already loaded.
effect
effect string 'show' Function name of the effect you want to use to show the loaded images, like show or fadeIn.
effectTime integer 0 Time in milliseconds the effect should use to view the image.
throttle
enableThrottle boolean true Throttle down the loading calls on scrolling event.
throttle integer 250 Time in milliseconds the throttle will use to limit the loading calls.
callbacks
beforeLoad function undefined Callback function, which will be called before the element gets loaded. Has current element and response function as parameters. this is the current Lazy instance.
afterLoad function undefined Callback function, which will be called after the element was loaded. Has current element and response function as parameters. this is the current Lazy instance.
onError function undefined Callback function, which will be called if the element could not be loaded. Has current element and response function as parameters. this is the current Lazy instance.
onFinishedAll function undefined Callback function, which will be called after all elements was loaded or returned an error. The callback has no parameters. this is the current Lazy instance.

Build and Validation

This project includes an automated build script using gulp. To build your own versions of Lazy you need to install it via npm first. Afterwards you can use the following command in your console to automatically generate all productive files. While building these files everything will be checked with jshint for validity too.

$ gulp build

Available gulp Tasks:

Name Description
build check & build everything
build-main check & build main project file
build-plugins check & build single plugin files
concat-plugins build concatenated plugins file
validate check all files with jshint
watch watches all files to check & build everything on change

Bugs / Feature request

Please report bugs and feel free to ask for new features directly on GitHub.

License

Lazy is dual-licensed under MIT and GPL-2.0 license.

Donation

You like to support me?
You appreciate my work?
You use it in commercial projects?

Feel free to make a little donation! ๐Ÿ˜‰

jquery.lazy's People

Contributors

canu667 avatar dkern avatar felixonmars avatar hosein2398 avatar marksto avatar pburke avatar sadraskol avatar zspitzer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.lazy's Issues

lazy.js loads all invisible images north of viewport

http://jsfiddle.net/xk6a24ej/ shows this effect for a page with 1000 images.

Problem

When you quickly scroll down to the end, and then up into the middle, you will see that all previous images are already loaded. This means, that all about 1000 images north of the viewport have been fetched, even if this was not necessary for showing the page at the end, and at the middle.

Compare with http://jsfiddle.net/uxmeejo1/ which uses https://github.com/ressio/lazy-load-xt and correctly handles this problem.

Related to my problem appears to be the comment http://jquery.eisbehr.de/lazy/#comment-1230029627

Problem: in your example http://jquery.eisbehr.de/lazy/... only the images in the viewport are loaded (2 or 3) whereas mine all are loaded ... Any idea why ?

where you answered

did you set an image width / height for the new loaded images? Otherwise the problem could be, that all images have a height of zero pixels and so fit all in your loadable area at once. At least specify a min-height or something.

http://jsfiddle.net/xk6a24ej/ has width and height set, but the problem is still present.

isInViewport / feature request

Hi @eisbehr- ,

first of all I want to thank you for this nice plugin.
I am using jquery.lazy with a custom loader, loading AMD Modules.

I wonder if it would possible to add a feature which tells the module/element
if it is in the viewport or not.

This could be useful for stopping sliders or a videos if they are out of scope.

Thank & regards

Ajax load

Hi,

great plugin you have developed...

I am using this in one page app, where i get new images on request. First page load, images do lazy load but when i get new response, the images are no not displayed...

i have tried following, nothing works

var instance = $('.lazy').lazy();
instance.update();

No images shown after ajax response.. ..can you help ?

Plugin not working on images loaded via AJAX

The lazy plugin works fine for the initially loaded elements but doesn't work for images loaded via AJAX despite having the code in done function of the AJAX call.

Here is my code for lazy loading images

jQuery(document).ready(function() {
    jQuery("img.lazy").lazy({
        effect: "fadeIn",
        effectTime: 1000
    });
});

Here is my AJAX call

$(document).ready(function() {
    $('#edmhunters_body').on('click', '#loadmore-dj', function() {
        $('#loadmore-dj').hide();
        $('#loadmore-dj-gif').css( "display", "block");
        $.ajax({
            type: "GET",
            url: "/loadmore/dj/",
            data: {
                'slug': $('.dj_slug').text().trim(),
                'song_rank': $("#dj_song_list").find('.song_block').length
            },
        }).done(function (response) {
            $(response).appendTo($('#dj_song_list')).hide().fadeIn(1000, function() {
                playOneAudio();
                jQuery("img.lazy").lazy({
                    effect: "fadeIn",
                    effectTime: 1500
                });
                $('#loadmore-dj').show();
                $('#loadmore-dj-gif').hide();
                hideLoadMore();
            });
        });
    });
});

Oddly though, if I click on the button that calls the AJAX function before the initial images are loaded, the images loaded via AJAX are lazy loaded.

JQuery :visible selector false on Safari

The JQuery document:

http://api.jquery.com/visible-selector/

States: 'Visible elements have a width or height that is greater than zero.' So an image tag:

<img class='lazy' data-src='path/to/img'>

Will return false failing "the lazy magic" conditional and it looks like Safari follows this to the tee. The work around is to add a width or height attribute to the image tag or set the 'visibleOnly' to false in the 'lazy' method call. The versions used:

Safari version 5.1.10 (6534.59.10)
jQuery version 1.8.3 and 1.9.0
jQuery Lazy version 0.1.11

Memory Leak

Hello,
How can I unbind or destroy lazy load from all binded elements?
I am loading images via ajax and binding the event to each image
$("img.lazy", "#categoryList").lazy({ bind: "event", effect: "fadeIn", effectTime: 250, delay: -1 });

the problem I have is: each time I click a button to load more images( some images are removed) its not releasing the bind event and the page becomes slower and slower and the memory increases.

if I don't use lazy load the page does not slow down after each ajax call when scrolling

Issues with ajax

@eisbehr- so i created a new issue :)

The problem is, when show more occurs and i try to re-instantiate lazy load it will not replace data-src to src anymore if the current lazy instance auto destroys itself before ajax complete. If i scroll fast and ajax complete fires before auto destroy and i do .addItems to current instance it works.

so it works if in console i see:

#addLazyItems
#onFinishedAll

it doesn't work if:

#onFinishedAll
#addLazyItems
export default class Comment {
  constructor() {
    this.initLazyLoad($('img.lazy'));
  }

  initLazyLoad($imgs) {
    this.lazyInstance = $imgs.Lazy({
      chainable: false,
      afterLoad(img) {
        img.removeClass('lazy');
      },
      onFinishedAll() {
        console.log('#onFinishedAll');
      }
    });
  }

  addLazyItems() {
    console.log('#addLazyItems');
    const $imgs = $('img.lazy');
    if (this.lazyInstance) {
      this.lazyInstance.addItems($imgs);
    } else {
      this.initLazyLoad($imgs)
    }
  }

  onShowMore() {
    this.showShowMoreLoader();
    $.ajax({
      type: 'GET',
      url: location.setQueryParam('page', ++config.paginate.page),
      dataType: 'json',
      success: this.onShowMoreSuccess.bind(this),
      complete: this.addLazyItems.bind(this)
    });
  }

}

Examples on you website - Basic Usage - Needs to be more explicit!

Hi. Just want to note (as a very first time user of lazy loading technique and your plugin in particular) that it took me ALMOST 2 HOURS to realize that i need to prepare images in specific, non-standard way. In the "Basic Usage" of the "Get Started" section it is NOT obvious for a first time visitor what "Just prepare your elements" means. I thought it means - just add your img tags or something. So i just created my test.html page, included all required scripts, added a lot of "img" rows and couldn't realize why it is not working. The only way i finally realized how everything works is by disabling javascript and seeing what happens before jQuery.lazy() plugin kicks in. So in short - just a simple suggestion - please explicitly add IN THE "Basic Usage" example of how img tag should be prepared. I admit i was lazy to read till the end of the "Getting Started" section, but "Basic Usage" section without providing an example of img tag is misleading IMO, so without knowing it i though the instruction was complete.

autoDestroy kills triggers for all Instances

I was building a page with two instances of Lazy, only slightly different by one event handler. However when I was loading the page showing elements of instance one, scrolling towards the elements of instance two, the latter ones never appeared. Same went if i tried the other way around.

The problem was fixed after setting: autoDestroy: false for both instances. Obviously when all items of a given instance are displayed the Lazy instance destroys itself. But it also destroys the scroll triggers for any other instance.

Happens to me using jquery.lazy-master under jQuery 1.11.3 on any brower.

Fail to be triggeredd with jQuery 1.8+

in the setup step:

        // set up lazy
        (function()
        {
            // if event driven don't wait for page loading
            if( configuration("bind") == "event" ) _initialize();

            // otherwise load initial items and start lazy after page load
            else $(window).load(_initialize);
        })();

the use of $().load() event handler is depreciated since jQuery 1.8: http://api.jquery.com/load-event/

shoud be changed to .on( "load", _initialize)

Doesn't work on iPad Air and Iphone 3

Lazy Load doesn't work on iPad Air and iPhone 3. Is there a workaround to get it fixed? Actually I check for mobile devices and disable lazy load at all, but I in fact I need that plugin for mobile devices to save bandwidth...

Base case Initialization issue

Hi,
I am trying to initialize lazy after page load and have images load when visible in the viewport, however despite the documentation after the page loads, all the images begin to load on the page even when not in the viewport. It loads images from the top of the page and cascades down regardless of where I am. I've tried adjusting various parameters such as threshold and setting visible only to no avail.
Interestingly, on page load, if my viewport is at the bottom of the page only those images load and as I scroll upward, the page exhibits the behavior I would expect from this library. (The images load consecutively after upward scroll). Do you know of a solution/ Is there a reason to explain this behavior?

Thanks

Tab container and loading

I have a unique situation here, maybe. I have a tab interface which contains - optionally - images. The open tab window (divs that hide and show based on the clicked tab) that contains an image loads when scrolled into view. Now, if I click on another tab, the image there does not load until I scroll the page a bit. I saw this (http://jquery.eisbehr.de/lazy/example_load-elements-by-events), thought maybe I could force load the image on the tabs click event. That example however would load the rest of the images not yet on the screen, which I'd rather not do. Is there something a little more precise that could be done?

Here is my JS:

    $.req.imageLazyLoad = function() {
        var effect      = $('body').data('lazyload-effect');
        var effectTime  = $('body').data('lazyload-time');

        $('.req-lazy').lazy({
            effect: effect,
            effectTime: effectTime,
            threshold: 0,

            afterLoad: function(element){
                setTimeout(function() {
                    element.addClass('load-finished');
                }, effectTime);
            }
        });
    };

Trigger loading with external call

I have pages where I am using Lazy that have areas that are hidden and shown via script, revealing hidden images, as well as other images that should load on scroll / resize as normal. When I expand one of these areas the images don't load until the page scrolls.

It would be nice if you can expose a method that I can call to force the load when I change the page layout. Right now I am using window.trigger('scroll') but that just feels wrong. I can't use a custom event because I want the normal behaviours to work too.

Does not work at all in IE11 when using jQuery 3.0.0

When using this library together with the current jQuery version (3.0.0), no images are lazy loaded in Internet Explorer 11.

It does work in Chrome with jQuery 3.0.0, and it also does work in IE11 with jQuery 1.x and 2.x, but it does not work in IE11 + jQuery 3.0.0.

The root of the problem seems to be that $(window).on(_load + "." + namespace) is not working anymore.

Safari problem

Hi, i am using this great plugin, but now i have a problem with it. When I open the page with Chrome everything is working. When i open the page with a Safari the images is not loaded. Sometimes the image is shown for a second but after that is gone. I have also ajax request that is build on #39. And after AJAX request is done all images are shown in Safari. I have been noticed one more strange thing. When i initialize a plugin I am set retinaAttribute : "data-srcx2", but when i check the the current instance setting I see retinaAttribute : "data-retina". After AJAX request it is still retinaAttribute : "data-retina" but images are loaded.

allow adding additional items to be lazy loaded

Would it be possible to add a new function to allow adding additional items to be lazy loaded,
I'd like to avoid multiple lazy plugin instances running for different content blocks when context is being dynamically loaded / generated?

It would probably need an autoDestroy: false option

lazy function is not getting recognised

Hi,I need help with lazy loading. I have tried your code for lazy loading. I have kept my div inside a div with class lazy and applied css style of display:none.

$(function() {
    $(".lazy").lazy({
        console.log("inside lazy function");
        afterLoad: function() {
            console.log("data is about to be loaded");
            $('.lazy').css("display","block");
        },
        onError: function() {
            $('.lazy').css("display","block");
            console.log('onError of lazyLoad');
        },
        onFinishedAll: function() {
            $('.lazy').css("display","block");
            console.log('lazy loading finished');
        }
    });
});

Also, i have called <script src="/cs/mysyf/jquery.lazy.min.js" / > befor ethe script.
And i am not getting any thing in the logs related to this

How to reforce load?

This plugin is GENIUS, however, we have an issue.

I am using it for an image gallery that is loaded in a modal. It works GREAT, except, when we try to filter the results. Filtering is simple - it shows and hides images on the page. The problem is if a filter is selected for an image that Lazy hasnt loaded yet (because it was below the scroll) then the loading image is shown and the image never loads.

We need a way to call Lazy again after a filter is clicked that will see which images are visible in the modal and load them. Is that possible?

item loop in _lazyLoadItems caches item length can cause exception

Because the length of the item array is being cached, it's possible for an exception to be triggered in _isInLoadableArea, "element is undefined" if a loader with a callback is used and the size of the item array is reduced by another round of _lazyLoadItems being executed which removes one or more items from the item array, whilst waiting for the loader to return.

https://github.com/eisbehr-/jquery.lazy/blob/master/jquery.lazy.js#L305

Loading image using css

Hi Eisbehr and Thanks for this nice plugin :)
I'm trying to use it but i'll have 2 questions please:
1- regarding the loading image, I'm currently using a css generated image (-webkit-animation) and was wondering how i can integrate it with your plugin.

2- i have read that using lazy loader, will prevent google from indexing images, is that true? if yes, is there an alternative?

Thanks in advance
Cheers

Image/Text Overlap

Hello,

I'm having a bit of an issue with images and text overlapping in IE (works fine in other browsers) when using this plugin. It doesn't always happen maybe 1/5 page loads this will occur. You can see how it looks here: http://screencast.com/t/grzRP19z7

This is the how lazy is called:

        $mt("img.lazy").lazy({
            bind: 'event',
            effect: "fadeIn",
            effectTime: 800,
            threshold: 50,
        });

So I changed the parameters like so:

        $mt("img.lazy").lazy({
            bind: 'event',
            effect: "fadeIn",
            effectTime: 0,
            threshold: 0,
        });

And now it initially overlaps, but re-adjusts properly after a bit of scrolling like so: http://screencast.com/t/yFqtykAldu4

I'm using default configs:

var configuration =
        {
            // general
            bind            : "load",
            threshold       : 500,
            fallbackHeight  : 2000,
            visibleOnly     : true,
            appendScroll    : window,

            // delay
            delay           : -1,
            combined        : false,

            // attribute
            attribute       : "data-src",
            retina       : "data-srcX2",
            removeAttribute : true,

            // effect
            effect          : "show",
            effectTime      : 0,

            // throttle
            enableThrottle  : false,
            throttle        : 250,

            // callback
            beforeLoad      : null,
            onLoad          : null,
            afterLoad       : null,
            onError         : null
        };

Is there any thing I should try changing to remedy this? I'm not very skilled with jquery, but I tried playing around with it to no avail. Thanks in advance.

chrome ignoring images with blank src=""

Following code is working in FF but not in Chrome:
<img id="testimg" data-src="big-image.jpg" src="" />

$("#testimg").lazy({
delay: 5000,
effect: 'fadeIn', 
effectTime: 1500
});

After debugging, I found that Chrome ignore images that contain blank "src" attribute. If I add dummy attributes to code above, the plugin works fine.

  1. <img id="testimg" data-src="big-image.jpg" src="dummy" />
  2. <img id="testimg" data-src="big-image.jpg" alt="dummy" />

Is there any workaround, I don't want to add dummy attributes just to make it work in chrome.

TIA

getItems() can returned handled items during processing

at the moment, getItems() just returns the internal items, without filtering out the handled items

thus, if you call getItems() in a custom loader before _lazyLoadItems has looped thru everything
and then subsequently filtered out the handled items, you will see some already handled items

Optimize cache and add default folder?

Hello. I use Lazy Load XT and looked for a fresh replacment.

1

I have optimize my XT with cache optimized:

    $('<img/>').attr('src', default_media + $this.attr(bgAttr) ).load(function(){
        //We load the image into an <img> and then immediately delete it once the image is loaded
        //Now that it's cached, when we set the bg-image it'll be instant.
      $(this).remove();

after set this (your code)

      $this
          .css('background-image', "url('" + default_media + $this.attr(bgAttr) + "')")
          .removeAttr(bgAttr);

2

Add a property for set a default media path. Its better as write every time a full path to CDN:
data-src="http://cdn.exemple.com/images/....."

3

The Option "visibleOnly" not working, when element is in overflow hidden div and not visible on screen, but in viewport and is(:visible) is true. Better, use this function:

// http://stackoverflow.com/a/15203639/706420
function isElementVisible(el) {
    var rect     = el.getBoundingClientRect(),
        vWidth   = window.innerWidth || doc.documentElement.clientWidth,
        vHeight  = window.innerHeight || doc.documentElement.clientHeight,
        efp      = function (x, y) { return document.elementFromPoint(x, y) };

    // Return false if it's not in the viewport
    if (rect.right < 0 || rect.bottom < 0
            || rect.left > vWidth || rect.top > vHeight)
        return false;

    // Return true if any of its four corners are visible
    return (
          el.contains(efp(rect.left,  rect.top))
      ||  el.contains(efp(rect.right, rect.top))
      ||  el.contains(efp(rect.right, rect.bottom))
      ||  el.contains(efp(rect.left,  rect.bottom))
    );
}

isElementVisible($(selector).get(0));

I hope this helps :)

Add custom class to the loaded image

Is there a possibility to add a class to each image, but only when the image itself is loaded? So, I will be able to add a css transitions when the image is loaded.

1.7 bug

cannot call "is" on null object. Looks like it's related to the buffer code you added. You're not ensuring that buffer !== null before calling buffer.is(":visible").

Using deprecated jQuery.error() method

Hi. I noticed that this plugin is using the jQuery.error() method which is deprecated since jQuery v1.8.

Here is a capture of the Chrome's console window. jquery-migrate plugin informs a deprecation notice.

image

I found this issue with the following setup;

  • jquery v3.1.0
  • jquery-migrate v3.0.0
  • jquery v1.7.1

Thanks.

Error at _isInLoadableArea function

I have unspecified errors in IE8 mode in IE11 at line:

var elementBound = element.getBoundingClientRect();
in function: function _isInLoadableArea(element)

I resolved it with code:

var elementBound = null;
try {
    elementBound = element.getBoundingClientRect();
} catch(e) {
    elementBound = { top : element.offsetTop, left : element.offsetLeft };
};

Can you update your source?

Images on tab loaded only after mouse move

When using tabs (http://unwrongest.com/projects/tabify/) after I click on tab my images does not load until I move my mouse.

I have tried to put an event:
$(".lazy-start").click(function() {
console.log('lazy start');
$("img.lazy").lazy({
bind: "event"
});
});

But it doesn't help.

It looks like that it cannot detect if tab switched it's content display from none to block;

Doesn't work with Flexbox style layouts

.layout-container {
height: 100vh !important;
position: relative !important;
width: 100% !important;
}
.layout-container {
height: 100%;
position: absolute;
width: 100%;
}
.layout-content {
display: flex;
flex-direction: column;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
position: relative;
width: 100%;
}
.page-content {
display: inline-block;
flex-grow: 1;
overflow-x: hidden;
overflow-y: auto;
z-index: 1;
width: 100%;
}

Doesn't work when using this style of layout. Has issue with overflow-x and y.

_item is not defined

Hi, I'm trying to lazy load images which src (data-src) is set dynamically depending on ajax results. The image Tags stay the same, just the source is changed.

The problem is that the images aren't loaded at all and when i check the _item variable from lazy I get an "is not defined" error.

var search_results = $(".search-results");
var artist_result = search_results.find('.result-artist img');
var museum_result = search_results.find('.result-museum img');
var painting_result = search_results.find('.result-painting img');

....

if(painting.name!=null) {
    if (painting.link == null)
        painting.link = "img/placeholder.png";

    painting_result.data('src', painting.link).data('name',painting.name).data('artist',painting.artist);
    search_results.find('.painting-name h5').text(painting.name.replace(/_/g, ' '));
}
else{
    painting_result.data('src', "img/placeholder.png").data('name','');
    search_results.find('.painting-name h5').text("");
}

search_results.show();

painting_result.lazy({
    bind: "event",
    delay: 0,
    visibleOnly: false,
    beforeLoad: function (element) {
        console.log("loading");
    }
});

The curious thing is when I use the painting_result selector itself, I can access the data without problems.

instance.loadAll() throws error

Init when ajax fetch data.
window.lazy = $("img.lazy").Lazy({
chainable: false
});

Trigger loadAll() when load more items form ajax. then call loadall in ajax callback.
window.lazy.loadAll();

Error***********
Uncaught TypeError: _event.e is not a function_instance.loadAll @ store.min.js:631g.updateImageLazyLoad @ store.min.js:781(anonymous function) @ store.min.js:828m.Callbacks.j @ store.min.js:2m.Callbacks.k.fireWith @ store.min.js:2x @ store.min.js:4m.ajaxTransport.send.b

Is lazyload waiting all html elements loading before running ?

Hello Daniel,

Thanks for your great works.

** The problem **
I don't know if my problem is really a bug but it could be annoying. I notice lazyload is waiting that html document is fully downloaded, before really loading pictures.

** Example **
Description

  • I have a page with a classical youtube reader in my page
  • lazyload is called in a jquery function (function($) {$("img.lazy").lazy();}}
  • I use some debug function and notice this beahviour
    • $("img.lazy").lazy() is called
    • the lazy picture are not loaded
    • youtube reader is full loaded
    • lazy picture start to load.

** Additionnal information **

  • lazyload v0.3.3 (min edition)
  • jQuery v1.11.0 (min edition)
  • tested with {chrome 37.0.2062.124, firefox 32.0.3} / win 7
  • tested with {chrome 38.0.2125.102, firefox 32.0.3} / Android 4.4.4
  • I also noticed this beahaviour when I used facebook javascript to display "like button" (I remove it now) :
    • html document is loaded
    • lazyload doesn't load lazy pictures
    • facebook javascript is loaded (it could take a long time)
    • lazyload start to load picture

Thanks to reading my message. I hope it could help you to improve your great lazyload

Use Lazy with CDN

Hi,
Sorry my message isn't really a bug but i didn't find where to write.
I'm already using your plugin and signed up for a CDN but it doesn't seem to be working in combinaison with Lazy, I'm using v0.6.4 and was wondering if there's a tweak for what i want to do.

Thanks a lot
Regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.