Tuesday, September 6, 2011

Lazy Loading


What is Lazy Loading?

Guess what? Server-side render time is probably not the bottleneck of your page performance… In most cases, the front-end is the most significant contributor to page load time. Things like img tags and css images are one of the most frequent contributors to load because these assets are loaded by the browser, even if they’re not visible to the user.
But you have all this content and images on your page, you say? What are you to do?
So one technique is to use lazy loading of images and even entire portions of the DOM as users scroll down the page. By lazy loading, you free up resources such as bandwidth, available http connections, and client-cpu to render the content within the browser viewport quickly. Then, worry about additional content as the user scrolls down the page.
Maybe there’s a little delay to load the images, but better to render them later than keep your users waiting on initial load, right? Who knows? Maybe many of your users don’t even scroll down on every page load? In those cases, they will never see the content anyway… why waste resources?
Perhaps you’ll also cut your server bandwidth and free up more apache threads or reduce requests to your static content server by using lazy loading and save yourself some Dinero$.

How To Implement Lazy Loading with jQuery

So I wrote this little jQuery plugin that I hope you’ll find useful to help in your endeavor to get lazy. The premise is to use a placeholder tag with an Html Comment inside to hide content from the rendering engine. If the browser can’t see your img tags or html elements with css images, it obviously wont render them.
The trick then is to tell the browser which tags to render while the page is loading.

Here’s a quick example:


–>

Any, html css img background, whatever.
–>


The Lazy Loader replaces the placeholder ‘pre’ tags with the text inside the HTML Comment, so the pre tags disappear as the hidden content is rendered into the DOM. This way, you don’t get a bunch of crufty markup cluttering up the DOM once the content is rendered.
If the content appears withing the browser viewport on initial load, the content in the pre tags is automatically rendered right away. Otherwise the html content within the pre tags is rendered as the user scrolls down the page.
I like to use pre tags for placeholders when I’m lazy loading because they render with 0 dimension when there’s only an html comment inside. You can use any tag you like though with your html comment inside. You can use div, li, ul, etc… not just pre tags. Be sure though not to include any white space between the tags:
not:
                               

A real Lazy Loader example – Facebook Friend List: