Lazy load for table

时间:2015-06-25 18:35:02

标签: javascript jquery

Setup:

So, I have a narrow but long table (width:200px, height:2000px ish). This table is wrapped inside another div with fix height (300px) and overflow-y:scroll, giving a fixed height visible area. In the table, there is a lot of cells that are stacked vertically (see image and markup is simple regular table wrapped in a div).

enter image description here

Problem:

Each cell contains images, so if there are lots of cells that the page has to fetch including the images and data before loading the site then it will slow down the site significantly.

Solution Approach:

I am thinking of two approaches.

  1. Apply lazy-load to images only. In this case (for example, from the image above). all three sections (section 1, 2 and 3) will be fully loaded except images that are not visible yet. Although it will minimize the delay if it has to fetch lots of data (for example 100+ cells), then I am not sure if it is the best approach.

  2. Another approach is little bit more complicated but will minimize the delay as much as possible and is really ideal. So, when the page is first loaded, only the section-1 will be visible but section-2 will be also loaded (either with images or lazy-loaded images. Howeversection-3will not be loaded at this point. When the user scrolls to thesection-2then thesection-3will be automatically loaded but not visible until user scrolls down. Ifsection-3is in the viewpoint, thensection-4` will be loaded but not visible. You get the point.

Any thoughts on it and how-to?

Thanks.

1 个答案:

答案 0 :(得分:2)

Do both. Make sure your images are always being lazy loaded, and only get the data for the next section when the user is scrolling and gets close to (or at) the bottom. I use a lazyload image system where I specify my images like this: <div class="lazyimg" data-src="path/to/image"> </div> I give .lazyimg a width and height and then, when it scrolls into view, I load data-src and set background-image on the .lazyimg element. This only works if you can specify a size independent of the actual image size, background-size: cover|contain are your friends here. EDIT Alternatively I guess you could load the image and then pop it in the DOM as an img tag, but changing the dimensions of the element could affect any sibling layout which could appear somewhat jarring, even if smoothly animated. How to do it: onscroll callback.