jQuery: using cookies to cache Twitter results
by gabrieleromanato
HTML
<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<div id="twitter-followers"></div>
JavaScript
(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);
$('#twitter-followers').twitterFollowers({
cookie: true
});