Javascript – Lazy loading items below the fold

In: Javascript

10 Jul 2012

Quite often there are a number of heavy items that are loaded on a web page which is located below the fold. These items such as flash movies located at the bottom of a page, or in some instances facebook activity feeds which are located below the fold, simply add to a pages load and response time.

This is especially true for website landing pages where users more often than not are only interested in clicking through to some feature article located above the fold.

Here is a “mini” javascript library which will allow you to lazy load these items below the fold when a user first scrolls down the page. I’ve tested it in IE7, IE8, IE9, FF, Chrome, Safari, Opera etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var Utilities = {
    RegisteredScrollFuncs: [],
    Timeout: 100,    
    GetScrollPosition: function() {
        var position = [0, 0];
        if (typeof window.pageYOffset != 'undefined') {
            position = [
                window.pageXOffset,
                window.pageYOffset
            ];
        }
        else if (typeof document.documentElement.scrollTop
            != 'undefined' && document.documentElement.scrollTop > 0) {
            position = [
                document.documentElement.scrollLeft,
                document.documentElement.scrollTop
            ];
        }
        else if (typeof document.body.scrollTop != 'undefined') {
            position = [
                document.body.scrollLeft,
                document.body.scrollTop
            ];
        }
        return position;
    },
    RegisterScrollListener: function(func) {
        this.RegisteredScrollFuncs.push(func);
 
        if(this.RegisteredScrollFuncs.length == 1)
            this.PollRegisteredListeners();
    },
    PollRegisteredListeners: function(e) {
 
        if (Utilities.GetScrollPosition()[1] > 0 && Utilities.RegisteredScrollFuncs.length > 0) {
            for (var i = 0; i < Utilities.RegisteredScrollFuncs.length; i++) {
                Utilities.RegisteredScrollFuncs[i]();
            }
            Utilities.RegisteredScrollFuncs = [];            
        }
        else {
            window.setTimeout(Utilities.PollRegisteredListeners, Utilities.Timeout);            
        }   
    },
    LoadFacebookActivity: function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=122480627837535";
        fjs.parentNode.insertBefore(js, fjs);
    }
}

The code above is actually very simple.

Stepping through the code

  1. RegisterScrollListener accepts a function as an argument and adds that function to an array.
  2. On the very first item which is added to the array it then kicks off the timer to poll the scroll bar position every 100ms.
  3. Once the scroll bar has moved, it will then run through the array of functions calling each one in turn.

And there we have it, a lazy polling solution that will allow us to perform any action that we desire when the user scrolls down the page.

Usage:

To use the library is very simple, there is no need to add anything to an onload method. Merely call

Utilities.RegisterScrollListener(callback);

where callback is a pre-defined function you want to occur once the user has scrolled down the page.

In this instance we’re going to load the facebook activity widget.

1
2
3
4
5
6
7
8
9
10
<div id="onfacebook" class="onfacebook"></div>      
    <script type="text/javascript">
        var onfacebook = '<h2>Your site on <b>Facebook</b></h2>'
                + '<div class="fb-like-box" data-href="http://www.facebook.com/YourSite" data-width="312" data-show-faces="true" data-stream="true" data-header="false"></div>';
 
            Utilities.RegisterScrollListener(function() {
                Utilities.LoadFacebookActivity(document, 'script', 'facebook-jssdk');
                document.getElementById("onfacebook").innerHTML = onfacebook;
            });            
    </script>

So there you have it, let me know if you find this useful.

Comment Form

About Justin

justin

Justin is a Senior Software Engineer living in Brisbane. A Polyglot Developer proficient in multiple programming languages including [C#, C/C++, Java, Android, Ruby..]. He's currently taking an active interest in Teaching Kids to Code, Functional Programming, Robotics, 3D Printers, RC Quad-Copters and Augmented Reality.

About This Blog

Software Engineering is an art form, a tricky art form that takes as much raw talent as it does technical know how. I'll be posting articles on professional tips and tricks, dos and donts, and tutorials.

profile for Justin Shield on Stack Exchange, a network of free, community-driven Q&A sites

Photostream

  • What I look for in a senior software engineer Justin Shield: […] I’m not going to list the design patterns that you’ll need, I’ve already [...]
  • Justin: Hi Ross, I do actually like Umbraco, it provides some nice abilities for creating websites that I [...]
  • Justin: Hi GordonBGood, Thanks for taking the time in replying. You're absolutely correct, it is turners s [...]
  • Ross Gallagher: Hi Justin, I'm a fellow Aussi looking to use Umbraco to create a simple website. I have downloaded [...]
  • GordonBGood: This is the "Turner Sieve" which **IS NOT** the Sieve of Eratosthenes (SoE) neither by algorithm nor [...]