views:

229

answers:

1

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()?

+2  A: 

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).

Sagi
+1 Was just going to post that.
Jeremy
Not working for me: I can make this work for files on my own server, but I'm actually accessing a file from a remote domain. When the file is from a remote domain, this is failing. It does complete, but it doesn't pass the XMLHttpRequest object into the complete function, so you end up with an 'xhr is undefined' error, which stops the script. If you don't try to access the XMLHttpRequest object, than you do successfully load the script from the remote domain, but you are stuck without access to the header information again.
Tom
Ok, that changes some things. Right now I don't have an idea, but you can at least store the md5 of each result and compare it to new data: `$(data).data('md5', md5(data))`
Sagi