且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery:动态图像处理(等待加载)

更新时间:2023-12-05 08:13:10

时尚,这一个是终于工作,并非常感谢Naugtur指向我正确的方向:

After trying to accomplish this task in just about every conceivable fashion, this one was the one that finally worked, and a big thanks to Naugtur for pointing me in the right direction:

var no_of_images = $('img').size();

$.extend(no_of_images);

if(no_of_images > 0) {

    var images = new Array();
    var i = 0;
    $('img').each( function() {
        images[i] = $(this).attr('src');
        i++;
    });

    i = 0;

    $(images).each( function(){
        var imageObj = new Image();
        imageObj.src = images[i];
        $(imageObj).load( function() {
            no_of_images--;
            i++;
            if(no_of_images == 0){
                functionToPerform();
            }
        });
    });
} else {
    functionToPerform();
}

为了快速解释发生了什么,我将使用类比。想象一下每个图像是你们聚会的客人。灯熄灭。你翻转灯光,然后比赛到每个客人​​,给他们一张纸,一支笔和一部手机,所有的时候统计你有多少人你提供的材料。他们都开始绘画,然后一旦他们完成他们的图纸,他们打电话给你,告诉你。对于每一个调用,你跨一个计数从你的董事会。当最后一个人打电话给你(当你的板子上没有标记的时候),你告诉他们挂断电话给披萨家伙。这是披萨时间。

For a quick explanation of what's happening, I'll use an analogy. Imagine each image is a guest at your party. The lights are out. You flip on the lights, then race to each guest and give them a piece of paper, a pen and a cell phone, all the while tallying how many people you handed materials out to. They all start drawing furiously and then as soon as they finish their drawings, they call you and tell you. For each one that calls, you cross a tally off your board. When the last person calls you (when you run out of tally marks on your board), you tell them to hang up and call the pizza guy. It's pizza time. If there were no guests to begin with, you call the pizza guy yourself.

如果你在想为什么他创建一个图片)$ c>每个 $。load()的对象,我试着去使用一个直接的jQuery风格的选择器,而不是传统的jQuery路由我尝试使用 Image() .onLoad $ c $结合使用c>,并且它不会崩溃页面,但它没有执行我写它的函数。

If you're thinking "Why did he create an Image() object for each $.load(), well, I tried going the traditional jQuery route of using a straight jQuery-style selector instead of the image Object. It was seemingly completely ignored (which crashed the page). I tried using Image() in conjunction with .onLoad, and that worked insofar as not crashing the page, but it didn't perform the function for which I wrote it.

这一段代码是自包含的,所以我想象它可以copypasta到任何图像加载应用程序。它看起来足够小,以便不被侵扰。 functionToPerform()基本上作为任何函数,你想等待,直到所有的图像加载(在我的情况下,它是整个插件)。Toodle。

This bit of code is self-contained, so I imagine it can be copypasta'd into any image-loading app. It seems small enough to me so as not to be intrusive. functionToPerform() basically acts as any function you would like to wait to perform until all images are loaded (in my case, it was the entire plugin). Toodles.