Lazily load elements becoming visible using jQuery

It is a useful trick to lazily load comments or such elements at the bottom of page. Some elements may be loaded only when they are scrolled visible.

  • All users are not interested in the information and do not necessary read the article long enough to see it
  • By lazily loading such elements one can speed up the initial page load time
  • You save bandwidth
  • If you use AJAX for the dynamic elements of the page you can more easily cache your pages in static page cache (Varnish) even if the pages contain personalized bits

For example, Disqus is doing this (see comments in jQuery API documentation).

You can achieve this with in-view plug-in for jQuery.

Below is an example for Plone triggering productappreciation_view loading when our placeholder div tag becomes visible.

...
<head>
  <script type="text/javascript" tal:attributes="src string:${portal_url}/++resource++your.app/in-view.js"></script>
</head>
...
<div id="comment-placefolder">

 <!-- Display spinning AJAX indicator gif until our AJAX call completes -->

 <p>
 <!-- Image is in Products.CMFPlone/skins/plone_images -->
 <img tal:attributes="src string:${context/@@plone_portal_state/portal_url}/spinner.gif" /> Loading comments
 </p>

 <!-- Hidden link to a view URL which will render the view containing the snippet for comments -->                       
 <a rel="nofollow" style="display:none" tal:attributes="href string:${context/absolute_url}/productappreciation_view" />

 <script>

 jq(document).ready(function() {

   // http://remysharp.com/2009/01/26/element-in-view-event-plugin/                                        
   jq("#comment-placeholder").bind("inview", function() {

     // This function is executed when the placeholder becomes visible

     // Extract URL from HTML page
     var commentURL = jq("#comment-placeholder a").attr("href");

     if (commentURL) {
     // Trigger AJAX call
       jq("#comment-placeholder").load(commentURL);
     }

   });                                     

 });     
 </script>
</div>

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

5 thoughts on “Lazily load elements becoming visible using jQuery

  1. Hi Mikko! I am positive to your effort, although I don’t myself have time to test it or contribute to it.

    Just some warning, after reading the remysharp page. If I were you I would check these…
    – Does it work with IE7, IE8?
    – Does it work with the new jquery 1.5?

    Best,

  2. We have it in production, targeting IE7 and IE8. We haven’t tested with JQ 1.5 yet, using JQ 1.3 which comes with Plone 3.

Leave a Reply

Your email address will not be published. Required fields are marked *