Reputation: 1038
I replace a background image using Javascript in an element by calling a local file (not a URL).
I want to try to catch an error if this file does not exist.
So I tried the following code:
try {
thing.style.backgroundImage = str;
}
catch (err) {
console.log(err.message);
thing.style.backgroundImage = "none";
}
However, even nonesense file names seem to pass and no error is generated. Even worse, sometimes the background image displayed is empty and sometimes it is an image from a previous call.
Is there any way to try/catch an error here?
Upvotes: 1
Views: 3344
Reputation: 2910
You could also try using AJAX instead of creating image objects and binding event listeners to the image's error and load events. While using AJAX, you could also rely on the status codes if you are using a service, or something that gives you dynamic images, it depends on how you want to manipulate everything.
Check out this bin, and see if it works for your use case.
http://jsbin.com/tezabupeli/18/edit?js,output
Upvotes: 1
Reputation: 12367
I'd take Barmar's recommendation and use an Image()
constructor to get the image. If you do that, you don't really need a try-catch; you can just call the appropriate function to set the background image.
You could do something like this:
var img = new Image();
img.src = "pathToImage";
img.onerror = function(){ // Failed to load
thing.style.backgroundImage = "none";
};
img.onload = function(){ // Loaded successfully
thing.style.backgroundImage = img.src;
};
Upvotes: 5