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

How to use jQuery.Lazy() Plugin with an image containing a cache-busting hash #252

Closed MicJarek closed 2 years ago

MicJarek commented 2 years ago

I am having a problem configuring jQuery.Lazy() to work with images that have been appended with a hash. In asp.net core Razor pages, you can use a Image Tag Helper so that the server appends the src with a hash that is checked/updated if the image is ever modified. The syntax is pretty straight forward:

For an <img>, simply add asp-append-version="true" and the server will auto-append the hash to the src. i.e.: <img src="/images/Photo.jpg" asp-append-version="true">

Which will show up in the browser as: <img src="/images/Photo.jpg?v=4jjcjhwsV9YZ1K8lXgg_50rci1ju_mNaz-HABqCvPFk">

The problem is: it can ONLY be applied to the src, and hence lies the issue. So when I add .lazy to the <img> like so: <img class="lazy" src="/images/PhotoPlaceholder.png" data-src="/images/Photo.jpg" asp-append-version="true">

.lazy works great (with the image fading in as expected), BUT the HTML is now this: <img class="lazy" src="/images/PhotoPlaceholder.png?v=4jjcjhwsV9YZ1K8lXgg_50rci1ju_mNaz-HABqCvPFk" data-src="/images/Photo.jpg">

Obviously, now the hash will NOT work because it's attached to PhotoPlaceholder.png instead of Photo.jpg. So, how do I configure jQuery.Lazy() to work with the hash?

Is this even possible? Or do I just have to pick one feature over the other? I need the version hash check because the images may be changed by users and therefore they need to be auto-refreshed (instead of everyone having to do a cache-emptying reload by hitting <ctrl> F5 on the page). I also understand browsers use/need the <src> to display the image (and not much can be done from that perspective), but ... wait...

After a good night's sleep mulling this dilemma over, I thought of a possible solution: For every <img> can we use a second hidden <img> tag to let the browser retrieve the (possibly changed) image first, before .lazy uses it to display the image in the first 'visible' <img>. Something like:

<img class="hide-control" data-src="<CommonPhotoIdentifier>" src="/images/Photo.jpg?v=4jjcjhwsV9YZ1K8lXgg_50rci1ju_mNaz-HABqCvPFk"> <img class="lazy" data-src="<CommonPhotoIdentifier>" src="/images/PhotoPlaceholder.png">

The 2 images could be associated with something like a data-src="", so that .lazy could identify/update the visible <img> using the hidden one. Is something like this doable?

dkern commented 2 years ago

I think this would be pretty easy by using a custom loader for Lazy. Just do a string operation and transfer the hash to the image url. Of course you need to implement the animation by yourself, but that should be easy too. ;)

It's untested, but something like this:

<img
  class="lazy"
  data-loader="hashedImageLoader"
  src="/images/PhotoPlaceholder.png?v=4jjcjhwsV9YZ1K8lXgg_50rci1ju_mNaz-HABqCvPFk"
  data-src="/images/Photo.jpg">
$('.lazy').Lazy({
    hashedImageLoader: (element, response) => {
        let hash = element.attr('src').split('?')[1];
        let src = element.data('src');

        element.attr('src', src + '?' + hash);
        response(true);
    }
});

More examples:

MicJarek commented 2 years ago

Well, that's kind of the idea, but I don't think this will work as you suggest. From what I understand, the hash is like a timestamp for the image file that is generated on the server and passed back to the client, where it is compared with the cached image file (if any). Because of this, the hash is specific to that file name (in this case Photo.jpg), so we can't simply split the hash and attach it to Photo.jpg on the client because that hash is for PhotoPlaceholder.png.

And that's why I suggested having a second 'hidden' img element (with the actual filename-specific hash) that will download and/or check/re-download the image first, before .lazy can do it's magic to display the hidden image in the visible <img>. Does that logic make sense?

So... is there a way to add this to .lazy so that other's could also benefit from it? I believe there are other tools (other than asp.net/core) that use this same hashing functionality. I don't know how complicated this would be to add, but if this was built directly into .lazy (again perhaps using 2 <img> working together), this would be a great selling feature... :)

dkern commented 2 years ago

If you have a hidden image field, the browser will directly load the image, so there is no lazy loading at all. This will not word. If you could save the src somwhere else it would be possible.

MicJarek commented 2 years ago

Well... (per your suggestion) I have found another element to get the hash. It turns out that you can also use the <link> element to generate the hash i.e. <link href="~/css/loader.css" asp-append-version="true" />, but instead of using a CSS file, I simply use the Photo.jpg, which produces a hash specific to that file (and it is the same hash as when used with an <img> tag: I verified it in the Browser source). A bit of a hack, but it seems to work.

Anyway... to test, I then altered your code to this:

<link class="hide-control" id="source-img-1" href="/images/Photo.jpg" asp-append-version="true">
<img class="lazy" id="img-1" data-loader="hashedImageLoader" src="/images/PhotoPlaceholder.png" data-src="/images/Photo.jpg" asp-append-version="true">

And that produces this when I view it in the Browser Source:

<link class="hide-control" id="source-img-1" href="/images/Photo.jpg?v=AAnmbJAusQ-go5lyg9qCes4WGj8oWsp4eGH78CKKUPA">
<img class="lazy" id="img-1" data-loader="hashedImageLoader" src="/images/PhotoPlaceholder.png?v=4jjcjhwsV9YZ1K8lXgg_50rci1ju_mNaz-HABqCvPFk" data-src="/images/Photo.jpg">

And the Jquery:

    $(".lazy").Lazy({
        effect: 'fadeIn',
        effectTime: 1000,
        hashedImageLoader: (element, response) => {
            let sourceHash = $('#source-' + element.attr('id')).attr('href');
            element.attr('src', sourceHash);

            let targetSrc = element.attr('src');
            let targetDataSrc = element.data('src');

            response(true);
        }
    });

When I look in the debugger, the sourceHash, targetSrc, and targetDataSrc are:

sourceHash = '/image/Photo.jpg?v=AAnmbJAusQ-go5lyg9qCes4WGj8oWsp4eGH78CKKUPA'
targetSrc = '/image/Photo.jpg?v=AAnmbJAusQ-go5lyg9qCes4WGj8oWsp4eGH78CKKUPA'
targetDataSrc = '/image/Photo.jpg'

So it looks like the code is setting the image src and the photo displays, but it's NOT easing in? Do I need to somehow set the effect another way?

dkern commented 2 years ago

If you use a custom loader, you have to do it yourself, because ... it's custom. ;) Untested, but somehow like this is the best way to do it for images.

$('.lazy').Lazy({
    hashedImageLoader: (element, response) => {
        let imageObj = $(new Image());
        imageObj.one('error', () => response(false)).one('load', () => {
            element.hide();
            element.attr('src', imageObj.attr('src'));
            element.fadeIn(1000);
            imageObj.remove();
            response(true);
        });

        let source = $('#source-' + element.attr('id')).attr('href');
        imageObj.attr('src', source);
        imageObj.complete && imageObj.trigger('load');
    }
});

But I also had another idea, but not sure if this works. But it should be. Maybe you want to test this approach, witch uses all Lazy functionalities.

$('.lazy').Lazy({
    effect: 'fadeIn',
    effectTime: 1000,
    beforeLoad: element => {
        let source = $('#source-' + element.attr('id')).attr('href');
        element.attr('data-src', source);
    }
});
MicJarek commented 2 years ago

Yes... that worked great! I tested the second (beforeLoad) one, and it is working as expected. Tks Daniel... šŸ˜Š

But... what I have learned since then, is that there is a way to actually append the data-src with the asp-append-version on the server using asp.net core. Just so others will benefit, in the page (or Partial View if retrieving via AJAX), simply add:

@using Microsoft.Extensions.DependencyInjection;

var versionProvider = Context.RequestServices.GetRequiredService<IFileVersionProvider>();

// Loop as needed for each file
PathFile = "/images/Photo.jpg";
PathFileWithHash = versionProvider.AddFileVersionToPath(Context.Request.Path, PathFile);
<img class="lazy" src="/images/PhotoPlaceholder.png" data-src="@PathFileWithHash" asp-append-version="true">

Pretty straight forward, allowing .lazy to work without any hacks or the <link> element... šŸ˜Š

I have another, quick question regarding using the .lazy with AJAX. I have a search page where the user can enter search criteria and click the 'Search' button. That triggers an AJAX .load() and when done (within the statusTxt == "success"), I then call:

$(".lazy").Lazy({
    effect: "fadeIn",
    effectTime: 1000,
    threshold: 0
});

What is happening, is that when the data is retrieved, the images do NOT start to fadein until I touch/drag the scroll bar on the side of the browser. How do I configure .lazy so that when the list is retrieved, the first few photos on top (the ones in the viewport) initially fadein?

dkern commented 2 years ago

Great that it works now. For your question. use the public functions of lazy.

let lazyInstance = $(".lazy").Lazy({
    chainable: false,
    effect: "fadeIn",
    effectTime: 1000,
    threshold: 0
});

lazyInstance.update();

I'll close this here now, as your question is solved.

MicJarek commented 2 years ago

Tks... šŸ‘

Although the public function is NOT working as you suggested. See: https://github.com/dkern/jquery.lazy/issues/253 for more info.