Reputation: 323
I have an application (a widget) where I use $.getScript() on a 5 minute timer, loading a file every five minutes. I then take the contents of the file I just downloaded, and rebuild my page, so that my widget can update. Most of the time, however, the file is unchanged, and firebug displays a 304 Not Modified header every 5 minutes, as my timer executes $.getScript().
I would like to sense when the file is not modified, so that I don't use up user resources, rebuilding the page for no reason.
Is it possible to obtain html headers when using $.getScript()?
Upvotes: 0
Views: 1582
Reputation: 8011
Instead of getScript(), use ajax() - which is more powerful and reduces function call.
Note that get(), post() and getScript() allow you to bind function to success only. In my opinion, using the ajax function instead of all the shortcuts is a good practice, because of the reasons I've mentioned.
You need the complete event because it provides you the xmlHttpRequest (XHR) object.
In order to achieve the same effect as getScript(), you have to add dataType: 'script'
to ajax options.
Now, you can use the complete event, to check the XHR code and return if it's not modified.
For example:
$.ajax({
url: 'your-url',
dataType: 'script',
complete: function(xhr) {
if (xhr.status == 304) return;
// or better: if (xhr.status != 200) return;
// your code goes here
}
});
You can't know in advance that the resource is not modified (if you don't have some logic in client side).
You must ask the server, which checks and sends 304 code early (so it's faster and reduces load from server).
Upvotes: 2