I'm pretty sure this exists, but I don't know what to search for:
I am refreshing content via JQuery's $('#somediv').load()
and another via $.ajax()
. I would like to catch situations where the new content is identical to the old content and slow开发者_如何学Go down the refresh rate.
I can imagine how to do it for the ajax
case - but seems like I'd have to store in memory a lot of data.
But what about load
?
jQuery's load
and $.ajax()
functions only fetch once. If you are refreshing constantly, you must be using a timer or a loop. Just clear the timer and set a new interval.
var refreshRateMs = 5000;
timerId = setInterval("refreshPage()", refreshRateMs);
function refreshPage() {
$("#somediv").load(); // Or other refresh code
}
// Later, you need to reduce the refresh rate (increase the interval):
clearInterval(timerId)
refreshRateMs += 1000; // Make delay 1s longer
timerId = setInterval("refreshPage()", refreshRateMs);
If you need to check using .load()
that the new content is not identical to the old content before appending it, don't use .load()
. .load()
has an implicit callback function that will load it into the dom. Instead, use $.get
:
$.get('page_to_load.html', function(data) {
var newContent = $('.result').html(data);
if newContent == $('.oldContent') { // Whatever check is necessary
$("#somediv").append(newContent);
}
});
From a performance perspective, would I be right in assuming that the answer Jasie has provided requires that the browser load the entire remote file so that it can check the contents against the locally stored variable?
A more efficient method if you're looking for efficiency might be using ajax because it can just check the header and use the last modified date. (Stuff I read here http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06)
Therefore a simple header check could be on repeat and then exit to a file reload only when modified date has changed.
I'm going to work on using this method and will post the results here when/if I get them working.
精彩评论