I have this simple chat tool to keep the chat room updated:
setInterval (loadLog, 2500);
function loadLog(){
//Scroll height before the request
var oldScrollHeight = document.getElementById("chatMessages").scrollHeight - 20;
$.ajax({
url: "/includes/chat/log.html",
cache: false,
success: function(html){
//Insert chat log into the #chatMessages div
$("#chatMessages").html(html);
var newScrollHeight = document.getElementById("chatMessages").scrollHeight - 20;
if(newScrollHeight > oldScrollHeight){
//Autoscroll to bottom of div
$("#chatMessages").animate({scrollTop: newScrollHeight}, 'normal');
}
},
});
}
Reliably executes approximately every 2.5 seconds. However I want to save bandwidth so...
I change:
cache: false
to
cache: true
And now it does not reliably execute every 2.5 seconds. (maybe each subsequent request is taking longer than the previous? maybe not, its behavior is very odd)
My research has yielded nothing. Please help! <3
If you enable caching the browser will cache the response from a previous call to the server and it will not make subsequent calls. That's expected and it is what this cache: true
attribute is designed for. If you want to reduce the bandwidth usage you might consider using a push technique rather than polling at regular intervals. This can be achieved using HTML5 WebSockets
. In this case the server will push a notification to the client whenever an update occurs rather than the client polling the server every 2.5 seconds. Obviously this will work only in browsers that support WebSockets so you might need to make feature detecting before using them if you need to support legacy browsers.