How to check if a file exists using JQuery

The best way to do this is with an AJAX HEAD request. HEAD requests only ask for and return the header from the destination file, so they’re much faster than POST or GET requests. Perfect for a simple file check.

It’s also worth noting that a HEAD request also returns the content length and last modified date, and that jQuery has an “ifModified” option for the .ajax function that returns a boolean value.

Quick code snippet:

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error:
        function(){
            //do something depressing
        },
    success:
        function(){
            //do something cheerful :)
        }
});

Couldn’t be easier!

Share and Enjoy:
  • Print
  • Digg
  • Google Bookmarks
  • email
  • StumbleUpon

Date: Wednesday, January 6th, 2010
Category: Web Dev

  • hdrnt
    cool. thanks for sharing this! I like the comments, especially.

    does it work as well if I want to check if a connection to the internet exists at the moment and only then reload the page with location.refresh(true)?

    will have to check this out when I'm back at my developing unit.. ;)
blog comments powered by Disqus
  • « Older Entries
  • Newer Entries »

Copyright © 2009 Rajeev Singh