Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't load images within hidden elements

This is not a duplicate of this because it also uses the document.ready approach which obviously does not work.

I want to avoid that the browser loads images (<img>) nested within hidden <div> elements.

So I tried this, however the javascript gets executed too late, the browser already starts to download images that it shouldn't.

  $(document).ready(function() {
    $('div').not(":visible").each(function () {
       $(this).find('img').each(function() {
         $(this).attr("src","");
       });
    });
  });

Is there a good javascript solution for this? Or do I have to use <img srctmp="...."/> and then replace srctmp by src via javascript for those images which are NOT nested within a hidden <div>?

like image 673
basZero Avatar asked Jul 23 '15 15:07

basZero


People also ask

Does display none improve performance?

Display none don't improve the performance because the goal of virtual scrolling is reduce the number of the elements into the dom. Make an element display none or remove an element, trigger a reflow, but with display none you worst the performance because you don't have the benefit of reduce the dom.

What is lazy loading image?

Lazy Loading Images is a set of techniques in web and application development that defer the loading of images on a page to a later point in time - when those images are actually needed, instead of loading them up front.

Does display none stop image loading?

Images or wrapper elements that have display: none set, will still get loaded. So if you want to eg. load a different image for desktop and mobile, you can either: use display: none , but with the loading="lazy" parameter set on img .

Are hidden images loaded?

Background images don't get loaded if the element is hidden.


1 Answers

You can use a data attribute instead the src, browser loads images only form src, so you can start with data-src for every images and then add the src only to the visible ones.

HTML:

  <img data-src="path/to/image.jpg" />

JS:

  $(document).ready(function() {
    $('div').is(":visible").each(function () {
       $(this).find('img').each(function() {
         $(this).attr("src", $(this).data("src"));
       });
    });
  });
like image 193
michelem Avatar answered Sep 21 '22 19:09

michelem