How can I implement lazy loading on a page with 500+ images?

风格不统一 提交于 2019-12-04 16:57:11

Web browsers are pretty smart at rendering pages efficiently so try this:

  1. Make sure you send the pixel size of the images in the HTML so the browser can render the whole page even when the images aren't loaded, yet.

  2. Fill up the URLs of the most important images right away (on the server) so the browser loads the images as fast as possible. For all other images, use a placeholder which says "Image is loading..." or something like that.

  3. On page-load, replace the placeholders with the real images in the background (load 2-3 images, then run yourself again with a timer waiting, say, 50ms).

You can further optimize step #3 by querying the size of the browser window and then ask the images for their position and only load them if they are visible.

Something like this perhaps:

<img lateSrc="/some/image.gif" />

<script>
$(document).ready(function() { 
    $('img[lateSrc]').each(function() { 
        var t = $(this);
        t.attr('src', t.attr('lateSrc')).removeAttr('lateSrc');
    });
});
</script>

How big are the images? An alternative approach might be to download them as one big tiled image then chop it up with css sprites or something similar.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!