1

I am developing a mobile app with HTML5, and I want to check if a file exists in the project structure(e.g. images/icon.png), I am new to H5 and javascript, I really need help.

Thank you in advance.

4 Answers4

8

Try to load it and listen to onerror event

var myImage = new Image();
myImage.src = 'images/icon.png';
myImage.onerror = function(){
   alert('not found');
}
Nader Roua
  • 611
  • 5
  • 9
2

You can check that using following code

<script>
var url = CheckUrl('images/icon.png');
if(url==true){
    //url exists    
}
else{
    //url not exists
}
function CheckUrl(url)
{
     if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    var http=new XMLHttpRequest();
     }
    else
    {// code for IE6, IE5
   var http=new ActiveXObject("Microsoft.XMLHTTP");
     }
    http.open('HEAD', url, false);
    http.send();
    return http.status!=404;
}
</script>
Sree KS
  • 1,311
  • 1
  • 13
  • 26
  • 1
    All these code responses now fail because either "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience". If you don't do async you still fail because Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///C:/jkerich_MyDocs/MMS/docs/html/html/fred. (Reason: CORS request not http)."". As for the new image way, it never says the file doesn't exist. So all the responses are now N/A for HTML 5. So what is the new way that works as for year 2020? – user3416126 May 22 '20 at 00:20
0

Need to be async to use await:

async function CheckUrl(url)
{
    const response = await fetch(url, {
    method: "head",
    mode: "no-cors"
  });
  return response.status == 200;
}
Community
  • 1
  • 1
pungggi
  • 1,263
  • 14
  • 25
-1

Hmm...imo, the best solution is the 2nd answer given in the post here:

How do I check if file exists in jQuery or pure JavaScript?

where it gives a jQuery-based solution:

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

The REASON I like the above solution is that the mechanism it uses is not encumbered by side-effects. i.e. does NOT need a XMLHttpRequest, which in turn seems to need "CORS" authorization or something else. (I spent over an hour trying such a method, and never could figure out how to get the XMLHttpRequest part to not fail.)

As always: "KISS" (Keep it simple, stupid)

MoD
  • 564
  • 4
  • 14
David
  • 2,253
  • 5
  • 23
  • 29