Asynchronously load images with jQuery

前端 未结 10 2174
日久生厌
日久生厌 2020-11-22 06:52

I want to load external images on my page asynchronously using jQuery and I have tried the following:

$.ajax({ 
   url: \"http://somedomain.         


        
相关标签:
10条回答
  • 2020-11-22 07:16

    No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:

    var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
        .on('load', function() {
            if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
                alert('broken image!');
            } else {
                $("#something").append(img);
            }
        });
    
    0 讨论(0)
  • 2020-11-22 07:18

    IF YOU REALLY NEED TO USE AJAX...

    I came accross usecases where the onload handlers were not the right choice. In my case when printing via javascript. So there are actually two options to use AJAX style for this:

    Solution 1

    Use Base64 image data and a REST image service. If you have your own webservice, you can add a JSP/PHP REST script that offers images in Base64 encoding. Now how is that useful? I came across a cool new syntax for image encoding:

    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhE..."/>
    

    So you can load the Image Base64 data using Ajax and then on completion you build the Base64 data string to the image! Great fun :). I recommend to use this site http://www.freeformatter.com/base64-encoder.html for image encoding.

    $.ajax({ 
        url : 'BASE64_IMAGE_REST_URL', 
        processData : false,
    }).always(function(b64data){
        $("#IMAGE_ID").attr("src", "data:image/png;base64,"+b64data);
    });
    

    Solution2:

    Trick the browser to use its cache. This gives you a nice fadeIn() when the resource is in the browsers cache:

    var url = 'IMAGE_URL';
    $.ajax({ 
        url : url, 
        cache: true,
        processData : false,
    }).always(function(){
        $("#IMAGE_ID").attr("src", url).fadeIn();
    });   
    

    However, both methods have its drawbacks: The first one only works on modern browsers. The second one has performance glitches and relies on assumption how the cache will be used.

    cheers, will

    0 讨论(0)
  • 2020-11-22 07:21

    use .load to load your image. to test if you get an error ( let's say 404 ) you can do the following:

    $("#img_id").error(function(){
      //$(this).hide();
      //alert("img not loaded");
      //some action you whant here
    });
    

    careful - .error() event will not trigger when the src attribute is empty for an image.

    0 讨论(0)
  • 2020-11-22 07:22

    If you just want to set the source of the image you can use this.

    $("img").attr('src','http://somedomain.com/image.jpg');
    
    0 讨论(0)
提交回复
热议问题