检查动态加载的图像是否完整 [英] Check if dynamically loaded images are complete

查看:70
本文介绍了检查动态加载的图像是否完整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码发布到php脚本中,该脚本读取文件夹中的所有文件并返回它们,它们都是img的,jquery解析信息,在var数组上,每个图像都保存为img对象.使用src,width,height和attr,成功后,我要检查是否加载了每个图像,然后最终在完全触发另一个函数并删除div.但我不知道如何检查图像是否已完全加载,我一直在鬼混.complete,但是似乎从未加载过,该函数在加载img之前一直调用itsef,然后返回true,这样它就可以保持去.这是代码,有点杂乱,可能不是很好的编码.

I have a code that post to a php script that reads all files in a folder and returns them, all of them are img's, the jquery parses the information, on a var that's an array each image is saved as an img object with the src , width, height and attr, on successed I want to check if each image is loaded and then finally on complete fire another function and remove a div. But I don't know how to check if the image has loaded completely, I've been fooling around with .complete but it never seem's to load, the function calls itsef upon until the img is loaded and then returns true so it can keep going. here's the code, it's kind of messy and probably not a nice coding.

var gAllImages = [];
function checkFed()

{
    var leni = gAllImages.length;   
    for (var i = 0; i < leni; i++) {


        if (!gAllImages[i].complete) {
            var percentage = i * 100.0 / (leni);
            percentage = percentage.toFixed(0).toString() + ' %';
            console.log(percentage);
            //  userMessagesController.setMessage("loading... " + percentage);
            checkFed();

            return;

        }

    //userMessagesController.setMessage(globals.defaultTitle);
    }
}


 if($('slideshow')){
 var topdiv = '<div id="loading"><div class="centered"><img src="/karlaacosta/templates/templatename/images/ajax-loader.gif" /></div> </div>';
    $('#overall').append(topdiv);
    //console.log('alerta');
    var jqxhr = $.post('http://localhost/karlaacosta/templates/templatename/php/newtest.php', function(data){



        var d = $.parseJSON(data);
        //console.log(d[1]);



        if(typeof(d) == 'object' && JSON.parse){
            var len = d.length;
            //console.log(len);



            for(var i = 0; i < len; i++){
                var theImage = new Image();
                var element = d[i].split('"');
                //        console.log(element);
                //      console.log(element[4]);
                theImage.src = '/karlaacosta/images/Fotografia/TODO'+element[0];
                theImage.width = element[2];
                theImage.height = element[4];                   
                theImage.atrr = element[6];
                gAllImages.push(theImage);

            }





        // console.log(html);
        }else{
            console.log('error');
        }
    }).success(function (){




    setTimeout('checkFed', 150);




    }).error(function(){
        var err = '<div id="error"><h2>Error: Lo sentimos al parecer no se pueden cargar las imagenes</h2></div>';
        $('#loading').append(err);

    }).complete(
        function(){
            var len = gAllImages.length;
            var html = '<ul class="slides">'    
            for(var i = 0; i < len; i++){
                html += '<li><img src="'+gAllImages[i].src+'" width="'+gAllImages[i].width+'" height="'+gAllImages[i].height+'" attr="'+gAllImages[i].attr+'" /></li>';


            }
            html += '</ul>';
            $('#slideshow').append(html);
        }
        );
 jqxhr.complete(function(){
    //
    imageSlide();
    $('#loading').remove();
    //
    console.log('completed');
});
}

如果我拿出checkFed()的递归性,显然脚本完成了,并且将图像放在html上时,它们又好又快地加载了,那么在缓存中就永远不会加载了吗?也欢迎代码其他部分的任何其他提示.

If I take out the recursivity of checkFed() obviously the script finishes and when the images are put on the html they are loaded fine and fast, are in the cache never being loaded? any other sugestions on other parts of the code are also welcomed.

推荐答案

我想检查每个图像是否已加载,然后最终在完全启动另一个功能并删除div.但是我不知道如何检查图像是否完全加载

I want to check if each image is loaded and then finally on complete fire another function and remove a div. But I don't know how to check if the image has loaded completely

从根本上来说,检查图像加载是否成功很简单:

Fundamentally, checking for image load success is simple:

var theImage = new Image();
var element = d[i].split('"');
$(theImage).load(function() {
    // The image has loaded (from cache, or just now)
    // ...do something with the fact the image loaded...
});
theImage.src = '/karlaacosta/images/Fotografia/TODO'+element[0];

上面的关键是在设置src之前,将load事件挂在 之前.如果先设置src且图像在缓存中,则load事件可能在钩住下一行代码之前触发,您会错过它.

The key thing above is to hook the load event before you set its src. If you set src first, and the image is in cache, the load event can fire before the next line of code hooking it, and you'll miss it.

这里是一个示例:实时复制 |

Here's an example: Live copy | source

HTML:

<img src="http://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG">
<p>When you see the image above, 
<input type="button" id="theButton" value="Click Me"></p>

JavaScript:

JavaScript:

jQuery(function($) {

  $("#theButton").click(function() {
    var img = document.createElement('img');
    $(img).load(function() {
      display("Image <code>load</code> event received");
    });
    img.src = "http://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG";
    document.body.appendChild(img);
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

如您所见,在每种情况下,我都使用相同的img src.可靠地,在我尝试过的每种浏览器上,我执行都会收到load事件.

As you can see, I'm using the same img src in each case. And reliably on every browser I've ever tried, I do receive the load event.

这篇关于检查动态加载的图像是否完整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆