Home > Software design >  How to apply referrerpolicy attribute with Lazyload with jQuery
How to apply referrerpolicy attribute with Lazyload with jQuery

Time:09-16

I set Lazyload script with jQuery with this code in my footer

<script>
    $(document).ready(function(){
    $("img.lazy").lazyload({
    threshold : 10,
    effect : "fadeIn",
    });
    });
</script>

And this is my HTML part of lazyload

<a href="https://www.example.com" target="_blank" width="100%" height="100%">
<img  src="//example.jpg" data-original="//example.jpg" referrerpolicy="no-referrer">
</a>

If I test without lazyload, refererpolicy works fine, but If I set with lazyload it seems that referrerpolicy attribute is not working. Is there any ways to set lazyload and refererpolicy together?

CodePudding user response:

lazyload 1.9.1 loads images in the background then updates your image with the background-loaded image. This allows it to provide a "loading..." type placeholder for when images take some time to load, rather than use the default browser image-not-found or image-loading image.

Lazyload does this with:

$("<img/>")[0].src = ...

ie, an in-memory image tag that doesn't exist in the DOM. When the load event of that in-memory image fires, lazyload then sets your img tag's src to the same as that of the in-memory image, thus using the cached version of the image.

As the $("<img/>") does not have a referrerpolicy, you get the default for that in-memory image tag: strict-origin-when-cross-origin.

The solution is to amend lazyload.js, line 105 to:

$("<img />", { referrerpolicy: $(this).attr("referrerpolicy") })

(there may need to be other checks as lazyload also works on non-images with background-image)

Obviously you then won't be able to use a CDN. Sample fiddle: https://jsfiddle.net/d954qtrm/2/


Note that lazyload v2.0 does not use an in-memory img tag so does not have the same problem and uses the source img referrerpolicy: https://jsfiddle.net/d954qtrm/3/

  • Related