Asynchronously load images with jQuery

前端 未结 10 2415
日久生厌
日久生厌 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:07

    You can use a Deferred objects for ASYNC loading.

    function load_img_async(source) {
        return $.Deferred (function (task) {
            var image = new Image();
            image.onload = function () {task.resolve(image);}
            image.onerror = function () {task.reject();}
            image.src=source;
        }).promise();
    }
    
    $.when(load_img_async(IMAGE_URL)).done(function (image) {
        $(#id).empty().append(image);
    });
    

    Please pay attention: image.onload must be before image.src to prevent problems with cache.

提交回复
热议问题