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.
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.
Try to load it and listen to onerror event
var myImage = new Image();
myImage.src = 'images/icon.png';
myImage.onerror = function(){
alert('not found');
}
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>
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)