D3.js version 5 Lazily loading DOM elements

In this example I demonstrate how you can lazily load DOM elements as you scroll through a page using D3.js.

In the below frame there are two SVG's to demonstrate the lazy loading of DOM elements. The left SVG is used to demonstrate the full "page" SVG. This is created at 10 times the size of the frame to force some scrolling. The right SVG shows a representation of the current view of the page. As you scroll down the elements are shown as they are loaded.

The elements in the blue area on the right SVG are those visible on the current page (the left SVG).

The elements in the red area are those that are pre-loaded before a viewer sees them. I have chosen to load 1.5 times the current view height above and below the current view window. This could easily be changed as needed to improve performance.

This example, as it is relatively simple, redraws at all scroll events. If you are performing intensive or large DOM operations you will want to buffer the scroll event for a period of time before beginning your operation. This will stop the interface locking up as large numbers of DOM updates are performed.

Example code and full tutorial

The full code is available by viewing the source of the below frame. If you want more detailed instructions there is my blog post I talk through the code step by step.