SoFunction
Updated on 2025-03-10

How to set an alternative path to an image using JavaScript

When doing web page development, sometimes I hope to set an alternative path for the image, that is, when the main path corresponding to the src attribute fails to load, the image can be switched to the alternative path immediately. In this way, even if the main path fails, displaying the alternate path will not affect the normal experience of the web page.

Note that a failed loading image in the web page will trigger an error event, so you can use the load and error events in the DOM model to achieve this effect.

src1='main/' //Main pathsrc2='another/' //Alternate path

jQuery before 1.8

Use load and error methods to catch events

$('#imgMap' ).attr("src",src1).load(function(){("Image loading successfully")        }).error(function(){
          ("Image loading failed, switch path")
          $('#imgMap').attr('src',src2)    
        });

jQuery 1.8

Since the load() method and error() method have been abandoned after jQuery 1.8, you can use the bind method to bind events

$('#img').attr("src",src1).bind( "load", function() {
 ("Image loading successfully")
}).bind("error",function(){
  ("Image loading failed, switch path")
      $('#img').attr('src',src2)  
});

jQuery 3.0

After jQuery 3.0, use the on method to capture events uniformly

$('#img').attr("src",src1).on( "load", function() {
 ("Image loading successfully")
}).on("error",function(){
  ("Image loading failed, switch path")
      $('#img').attr('src',src2)  
});

JavaScript

You can also call JavaScript native methods when you don't want to use the jQuery plugin. Use the addEventListener method to listen for events.

var Image = ('img');
=src1;
('load', function(event) {
       ("Image loading successfully")
});
('error', function(event) {
      ("Image loading failed, switch path")
       =src2;
});

The above is the method of setting alternative paths for an image using JavaScript that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!