dkern / jquery.lazy

A lightweight, fast, feature-rich, powerful and highly configurable delayed content, image and background lazy loading plugin for jQuery & Zepto.
http://jquery.eisbehr.de/lazy
Other
1.02k stars 236 forks source link

Delay between ready and beforeLoad #181

Closed machinefloor closed 5 years ago

machinefloor commented 5 years ago

I have been investigating an issue whereby the scripts are loaded and the DOM Is ready but a delay still exists until the beforeLoad event is triggered on images that are already in the viewport, or that have been scrolled to quickly after loading the page. It is most evident on big, image heavy pages on slower connections (e.g 4G).

I have tried disabling the throttle - I didn't quite understand what it does but it doesn't seem to have an affect. I have also tried increasing the threshold to 1000 but this hasn't helped.

Is there some kind of buffer or batching in place? Is lazy waiting for something like a ready or onload event before it begins processing images?

In order to speed things up I have moved the main jquery JS and lazy JS scripts into the head and also added the lazy() selector initialization immediately after the last lazy image. It hasn't helped, and this adds credence to the theory that the issue must relate to some delay (deliberate or due to too many queued images) within the lazy() logic.

A quick example to demonstrate the delay:

$(".lazy").each(function () {
    console.log("lazy image found");

    $(this).lazy({
        beforeLoad: function(element) {
            console.log("lazy image being handled");
        }
    });
});

I realize this isn't an efficient way to call lazy (I normally just use $(".lazy").lazy() too).

The console output looks a bit like this:

lazy image found
lazy image found
lazy image found
lazy image found
lazy image found
lazy image found

...seconds delay...

lazy image being handled
lazy image being handled
lazy image being handled
lazy image being handled

Upon further examination, reducing the number of lazy images doesn't seem to help either. For example, when I do this $("lazy").slice(0,10).lazy() (to handle just 10 images) I get a similar lengthy delay between lazy image found and lazy image being handled.

Thanks, Tom

dkern commented 5 years ago

Hello @machinefloor

That is interesting but i think that might because many party of are asynchronous and JS is a basically single threaded. Since jQuery 3 (if you use this) the ready state is async. Then, Lazy uses onLoad event to wait for other resources to be loaded before it. And then, the callbacks of Lazy are async too, beacuse lazy should load the images as fast as possible and the after callbacks have a lower priority.

If you don't want to wait for onLoad you can set the bind parameter to event. This will start Lazy directly. But the other things will remain untouched.

machinefloor commented 5 years ago

Thank you, I will try this!