Asynchronously load images with jQuery

前端 未结 10 2420
日久生厌
日久生厌 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 = $("").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);
            }
        });
    

提交回复
热议问题