jQuery: using cookies to cache Twitter data

jQuery: using cookies to cache Twitter data

How to cache our Twitter results by using cookies with jQuery.

Cookies can actually be used to store small portions of data taken from our web pages. Twitter data are an excellent example of this. For example, instead of keeping on retrieving the number of your Twitter followers from the JSONP API, you can simply fetch such data only once and store it within a cookie. This will actually improve the overall performance of your site. Let's see how we can accomplish this task with jQuery.

We only need the jQuery Cookie plugin to set and read the cookie's value which will simply contain a number. Then we can implement a simple plugin:

(function($) {
    $.fn.twitterFollowers = function(options) {

        var that = this;
        options = $.extend({
            username: 'gabromanato',
            cookie: false
        }, options);
        var apiURL = 'https://api.twitter.com/1/users/show.json?screen_name=' + options.username + '&callback=?';

        return that.each(function() {

            if (!options.cookie) {

                $.getJSON(apiURL, function(data) {

                    $(that).text(data.followers_count + ' followers');

                });

            } else {

                if ($.cookie('followers') !== null) {

                    $(that).text($.cookie('followers') + ' followers');


                } else {

                    $.getJSON(apiURL, function(data) {

                        var followers = data.followers_count;
                        $.cookie('followers', followers, {
                            expires: 1
                        });



                        $(that).text($.cookie('followers') + ' followers');

                    });



                }


            }




        });

    };
})(jQuery);

Our cookie has a lifespan of one day, just enough to spare some AJAX calls to the Twitter's API. Example:

$('#twitter-followers').twitterFollowers({
    cookie: true
});​

You can see the demo below.

Demo

Live demo