0

I need to eliminate image render-blocking and i use this little script for this

<img data-src>

$('img').each(function() {
    $(this).attr('src', $(this).data('src'));
});

It is good for all browser or it is better to use this plugin https://plugins.jquery.com/lazyload/ ?

Miky
  • 109
  • 2
  • 10

3 Answers3

1

You could add this CSS rule to avoid the broken image icon showing up :

img[src=''],
img:not([src]) {
    opacity: 0;
}

This way, images with no src won't show.

1

Your code should work in all browsers, but you may want to use some of that Lazy Load Plugin features. For example, it is able to load images when they’re really needed (that is, lazy), not when they’re outside of user-visible area. Your code will try to download all images at the same moment, even if no one is needed.

Consider adding support for robots or users that do not have JavaScript enabled:

<noscript>
  <img alt="…" src="…"/>
</noscript>

<img alt="…" data-src="…"/>
gsc
  • 1,559
  • 1
  • 13
  • 17
1

Actually, browsers by default load images somewhat lazily. An image on top of web page does not suspend rendering of remaining parts. As Image data is fetched from server browsers paint the reserved space for images in parallel to rendering the other elements.

Your code generates an image and loads it without attaching it to DOM. It is not lazy loading, it may be pre-loading in some context.

Lazy loading is: not beginning to download images from server until their reserved space is visible on browsers view-port. It is used in cases like your page is longer than the view port and there are images whose position stays at a lower portion of the page. Until you scroll to that position you don't load the images.

So if you want to use benefits of lazy loading you should choose the plugin option.

ihpar
  • 666
  • 4
  • 14
  • Yep sorry. But i have only 10 images 200x100 per page, i need just to load image after all for speed up the page, you think its a good idea to add a plugin for only 10 images per page ? – Miky Aug 10 '17 at 11:35
  • @Milky I think for 10 small-ish images, there won't be any problems without implementing any lazy loading. For speeding up page load times without any lazy loading implementation I would suggest compressing images with tools such as https://tinyjpg.com/ . But if you still need to load images after loading everything else have a look at these https://stackoverflow.com/questions/12396068/speed-up-page-load-by-deferring-images and https://varvy.com/pagespeed/defer-images.html – ihpar Aug 10 '17 at 13:01