Lazy Image Loading - Do it with D3

351 views
Skip to first unread message

Anand Venkataraman

unread,
Dec 4, 2011, 12:33:43 AM12/4/11
to d3-js
I'm lucky to have stumbled upon D3 when I was looking for a good
implementation of force-directed layouts for certain kinds of graphs.
I now use it for many more things than graph rendering. As an example
of how D3 has helped me greatly simplify things I'd hitherto put
together using plain ol' javascript and jQuery, Here's an adaptation
in D3 of a lazy image loader I'd written last year. The old code was
over 50 lines long and not as simple as befits an obviously simple
task such as lazy loading.

Now, using D3, the JS code is just a few simple lines (with scope for
further improvement :-) Here's a panel that contains "an infinite"
number of images.

<!DOCTYPE html>
<html>
<head>
<title>Do it with D3 - Lazy Loader</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/
d3.js?2.6.0"></script>
<style>
#lazyDiv { border: 1px solid #ccc; width: 400px; height: 200px;
overflow-y:scroll; margin: 10px auto 10px auto; }
body {text-align:center; font-family:"Trebuchet MS",Arial,Sans-
serif;}
h3 {color:darkgreen;}
</style>
</head>
<body>

<h3>Do it with D3 - Lazy Loading of images is now a breeze</h3>
<div id=lazyDiv onscroll=addMoreImages()></div>

<script>
var totalImages = 0;
addMoreImages();

function addMoreImages() { // onScroll callback
var numToAdd = 10;
var lazyDiv = d3.select('#lazyDiv');

// Always add content if div is empty. Otherwise, only add if
the height of the
// not-yet-scrolled-out content is less than the height of the
div (actually we use 2x div
// height because some browsers microfubar a div's pixel height
when zoomed in or out)

if(totalImages > 0 && lazyDiv.property('scrollHeight') -
lazyDiv.property('scrollTop') > 2*lazyDiv.property('clientHeight'))
return;

d3.select('#lazyDiv').selectAll(null)
.data(new Array(numToAdd))
.enter().append('div')
.html(function() {
var gChartBase = "https://chart.googleapis.com/
chart?chst=d_bubble_icon_text_big_withshadow&chld=snack|bb|";
return ("<img src=" + gChartBase + "only+$" +
totalImages++ + ".99|ffffff|000000 >");
})
;
}
</script>
</body>
</html>

I've <a href=http://pandamatak.com/people/anand/demo/lazy> placed a
demo here. </a>

I do have a question - is selectAll(null) ok? or will it throw an
exception in future?

Thanks!

&


Reply all
Reply to author
Forward
0 new messages