jQuery:有什么建议如何按顺序预加载 dom 中的所有图像吗?

发布于 2024-10-05 09:18:30 字数 46 浏览 5 评论 0原文

有什么想法吗?有什么插件吗?我想找到所有 img 标签并按顺序显示它们? 谢谢

any ideas about it? any plugin? I want find all img tag and show them sequentially?
thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甲如呢乙后呢 2024-10-12 09:18:30

创建一个小的 jQuery 实用方法:

jQuery.preloadImages = function() {
    var set = jQuery('img');
    var current = 0;
    var iterate = function() {
        var current_src = set[current].src;
        var temp = jQuery('<img/>');
        jQuery(temp).bind('load', function() {
            console.log($(this).attr('src') + ' loaded');
            jQuery(this).remove(); //remove temp image from DOM.
        });

        temp[0].src = current_src;
        jQuery('body').append(temp);
        if(++current < set.length) iterate(); //recursive call
    };
    iterate();
};

像这样调用它:

$.preloadImages();

jsFiddle 示例

Create a small jQuery utility method:

jQuery.preloadImages = function() {
    var set = jQuery('img');
    var current = 0;
    var iterate = function() {
        var current_src = set[current].src;
        var temp = jQuery('<img/>');
        jQuery(temp).bind('load', function() {
            console.log($(this).attr('src') + ' loaded');
            jQuery(this).remove(); //remove temp image from DOM.
        });

        temp[0].src = current_src;
        jQuery('body').append(temp);
        if(++current < set.length) iterate(); //recursive call
    };
    iterate();
};

Invoke this like such:

$.preloadImages();

jsFiddle example

简美 2024-10-12 09:18:30

浏览这个

Go through this

ˉ厌 2024-10-12 09:18:30

我在网站上使用此功能按特定顺序顺序预加载图像列表:

它还维护一个进度指示器。

MicrositeMedia.ImagePreLoader = function (_settings) {
var self = this;

var defaults = {
    list: [],
    rootpath: '',
    onFinished: function () { },
    onItemFinished: null,
    containerId: '#preload-container'
}

this.settings = $.extend(defaults, _settings);
this.progressElm = 'preloadProgressIndicator';
//this.settings.list.pop();
var listSize = _settings.list.length;

MicrositeUtils.Logger.log("listSize: " + listSize);

this.current = 0;

this.init = function () {
    //MicrositeUtils.Logger.log("ImagePreLoader - init()");
    // 
    $(this.settings.containerId).show();
    this.loadNext();
}

// list of already loaded items
var loadList = [];
var curImg = new Image();

this.loadNext = function () {
    if (listSize && listSize != 0) {
        // our current Image object
        var key = this.settings.list.shift();


        curImg.src = this.settings.rootpath + key;

        curImg.onerror = function () {
            //this.loadNext();
            MicrositeUtils.Logger.log("Error while loading image" + curImg.src.toString());
        }

        //MicrositeUtils.Logger.log('curImg.src: ' + curImg.src);
        // when it loads, it triggers the next load event.
        curImg.onload = function () {
            // item loading finished                
            //MicrositeUtils.Logger.log("current: " + key + ", src :" + curImg.src + "current: " + self.current);
            loadList.push(curImg.src);

            // fire single item loaded event.
            if (self.settings.onItemFinished) {
                self.settings.onItemFinished(self.current, curImg.src);
            }

            // next
            self.current += 1;

            // update loader progress indicator.
            self.updateProgressIndicator(curImg.src, self.current, listSize);


            MicrositeUtils.Logger.log("loading image " + self.current + "/" + listSize);
            if (self.current == listSize) {
                // last element has loaded, fire the complete event
                self.complete();

            }
            else {
                // call the next one recursively
                self.loadNext();

            }

        };

    }
    else {
        MicrositeUtils.Logger.log("ImageLoader.loadNext(): nothing to load!");
    }
}


this.complete = function () {

    // clean up
    $(this.settings.containerId).fadeOut('slow', function () {
        // last element has loaded, fire the onfinished event
        if (self.settings.onFinished) self.settings.onFinished();
    });

}

this.updateProgressIndicator = function (text, idx, max) {
    var elm = this.progressElm;
    var percent = (Math.round((idx / max) * 100)) + "%";

    if (!document.getElementById(elm)) {
        // insert element
        $('<div id="' + elm + '"></div>')
            .appendTo(this.settings.containerId);
    }

    //MicrositeUtils.Logger.log(percent);
    $('#' + elm).html(percent);
}

我这样称呼它:

this.imagePreloader = new MicrositeMedia.ImagePreLoader({
        list: preloadList,
        rootpath: self.appPath + '/assets/images',
        onFinished: function () {
            //MicrositeUtils.Logger.log("Preload (onfinished) - all done!");
            self.LoadInitialSection();
        },
        onItemFinished: function (item, src) {
            //MicrositeUtils.Logger.log("Preload (onitemfinished) - [item, src]: [" + item + ", " + src + "]");
        }
    });

    this.imagePreloader.init();

list 是图像名称的数组。

rootpath,顾名思义,是您需要预加载的所有图像的路径前缀。一般来说,这是您的应用程序的图像路径。

如果您想使用背景和进度指示器,containerId 是您的预加载器容器。如果您只需要在后台预加载,请将其设置为空字符串。

onFinished 通常包含一个在所有预加载完成时触发的函数。通常,您可以在此时展示您的图像。

onItemFinished 是在加载每个图像后需要触发的函数。

您可以省略 MicrositeUtils.Logger.log 函数或仅使用您自己的例程实现它。

I used this function on a website to preload a list of images in a specific order sequentially:

It also maintains a progress indicator.

MicrositeMedia.ImagePreLoader = function (_settings) {
var self = this;

var defaults = {
    list: [],
    rootpath: '',
    onFinished: function () { },
    onItemFinished: null,
    containerId: '#preload-container'
}

this.settings = $.extend(defaults, _settings);
this.progressElm = 'preloadProgressIndicator';
//this.settings.list.pop();
var listSize = _settings.list.length;

MicrositeUtils.Logger.log("listSize: " + listSize);

this.current = 0;

this.init = function () {
    //MicrositeUtils.Logger.log("ImagePreLoader - init()");
    // 
    $(this.settings.containerId).show();
    this.loadNext();
}

// list of already loaded items
var loadList = [];
var curImg = new Image();

this.loadNext = function () {
    if (listSize && listSize != 0) {
        // our current Image object
        var key = this.settings.list.shift();


        curImg.src = this.settings.rootpath + key;

        curImg.onerror = function () {
            //this.loadNext();
            MicrositeUtils.Logger.log("Error while loading image" + curImg.src.toString());
        }

        //MicrositeUtils.Logger.log('curImg.src: ' + curImg.src);
        // when it loads, it triggers the next load event.
        curImg.onload = function () {
            // item loading finished                
            //MicrositeUtils.Logger.log("current: " + key + ", src :" + curImg.src + "current: " + self.current);
            loadList.push(curImg.src);

            // fire single item loaded event.
            if (self.settings.onItemFinished) {
                self.settings.onItemFinished(self.current, curImg.src);
            }

            // next
            self.current += 1;

            // update loader progress indicator.
            self.updateProgressIndicator(curImg.src, self.current, listSize);


            MicrositeUtils.Logger.log("loading image " + self.current + "/" + listSize);
            if (self.current == listSize) {
                // last element has loaded, fire the complete event
                self.complete();

            }
            else {
                // call the next one recursively
                self.loadNext();

            }

        };

    }
    else {
        MicrositeUtils.Logger.log("ImageLoader.loadNext(): nothing to load!");
    }
}


this.complete = function () {

    // clean up
    $(this.settings.containerId).fadeOut('slow', function () {
        // last element has loaded, fire the onfinished event
        if (self.settings.onFinished) self.settings.onFinished();
    });

}

this.updateProgressIndicator = function (text, idx, max) {
    var elm = this.progressElm;
    var percent = (Math.round((idx / max) * 100)) + "%";

    if (!document.getElementById(elm)) {
        // insert element
        $('<div id="' + elm + '"></div>')
            .appendTo(this.settings.containerId);
    }

    //MicrositeUtils.Logger.log(percent);
    $('#' + elm).html(percent);
}

}

I called it like this:

this.imagePreloader = new MicrositeMedia.ImagePreLoader({
        list: preloadList,
        rootpath: self.appPath + '/assets/images',
        onFinished: function () {
            //MicrositeUtils.Logger.log("Preload (onfinished) - all done!");
            self.LoadInitialSection();
        },
        onItemFinished: function (item, src) {
            //MicrositeUtils.Logger.log("Preload (onitemfinished) - [item, src]: [" + item + ", " + src + "]");
        }
    });

    this.imagePreloader.init();

list is the array of image names.

rootpath is, as the name suggests, a the path prefix for all the images you need to preload. It's your application's images path, in general.

containerId is your preloader Container, if you want to use a background and a progress indicator. If you need only preloading in the background, set this to en empty string.

onFinished contains normally a function which fires, when all preloading is finished. Typically, you can present your images at this point.

onItemFinished is a function you need fired after each image loaded.

You can omit the MicrositeUtils.Logger.log function or just implement it with your own routine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文