How do I check if file exists in jQuery or pure JavaScript?
Want a one-liner? Use JavaScript's fetch
API. It sends a request and if the response's status
is 200, bingo, the file exists. Here's the magic spell:
Magic of $.ajax() in jQuery
If you are godfather of jQuery, then $.ajax
method with type: 'HEAD'
is your quicksilver wand. Why? It's like a Greyhound, fast and doesn't exhaust resource.
Old School: XMLHttpRequest
No jQuery? No problem. Use an XMLHttpRequest with the HEAD
method. It may sound like dinosaur but still roars loud enough.
Picture Perfect: Image object
Here's a left-fielder. JavaScript's Image
object could be used to check image file existence. If file loads, we have a Homerun!
Danger zones and rescue operations
Errors and compatibility issues are like kryptonite, they will bring down your Superman code. But we got your back!
Asynchronous operations and HTTP status to the rescue
The fact that asynchronicity makes your script super-speedy and checking HTTP status code acts like GPS for your file finding mission.
Watch those borders: Cross Origin Issues
Taking a leap with cross ORIGIN resources? Make sure the server is not a Gatecrasher and allows CORS Headers, else your checks might end up fighting shadows.
Don't hang, Go Asynchronus
People shun synchronous XMLHttpRequest like Monday mornings. They slow down user experience. I mean, who likes traffic jams, right? Always go asynchronous way.
Binary, Non-text files and Images
Just because we were playing with text files doesn't mean we forgot about the other kids on the block.
Binary Files: Blob and Array Buffer
Playing with Binary data? Check for existence similar to text files but go easy on bandwidth by adjusting the request.
Image files: The Height Matters
Checking if an image file exists? Bet you didn't know this, validating the height
property of an Image
object does the trick. It feels tall when the load is successful.
Stay Safe, Stay Fast, and Always Remember
Security First
While on this file existence check, don't let your guard down. Stay out of alleyways aka sensitive paths. Don't just rely on client-side checks for critical applications.
Need for Speed
Checking for file existence is not a Sunday drive. So use HEAD
method, it's like F1 race car, picks up headers without the need to download file, saving bandwidth and time.
Cache is King
Avoid repetitive checks and load on the server by implementing caching techniques. It's like your own fast food takeaway window for quick serving.
Was this article helpful?