I'm designing a simple SPA.
It shall use angular.js.
It shall not use any server side code.
The web app shall show a number of slides in a carousel.
The slides shall be placed in the img/slides
subdir of the app root dir.
The slides shall be named 1.jpg
, 2.jpg
, ... N.jpg
.
The number of the slides should be detected by the app at runtime, since the slides will be possibly uploaded or removed after the code is deployed.
This is the code I'm using to count the slides available on the server where the app is run:
// detect the number of available slides
var slidesCount = 0;
var slidesMax = 100;
for (var i = 0; i < slidesMax; i++) {
var url = 'img/slides/' + (1 + i) + '.jpg';
var request = new XMLHttpRequest();
request.open('HEAD', url, false);
request.send();
if (request.status === 200) {
slidesCount++;
} else {
break;
}
}
This code just works, but I'm not completely satisfied with it, since - on the first not found slide - it spits an error on console:
HEAD http://localhost/spa/img/slides/7.jpg 404 (Not Found)
I did try to use a try - catch block around open(); send()
, with no success...
So the question: can you suggest some way to avoid the error to be thrown to console, OR, an altogether different algorithm?