栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery Ajax等待所有图像加载完毕

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery Ajax等待所有图像加载完毕

@alex编写的插件由于某些原因对我不起作用…我不知道为什么。但是他的代码确实鼓舞了我想出一个对我有用的更轻量级的解决方案。它使用jQuery
Promise。请注意,与@alex的插件不同,它不会尝试考虑元素上的背景图片,而仅考虑img元素。

// Fn to allow an event to fire after all images are loaded$.fn.imagesLoaded = function () {    // get all the images (excluding those with no src attribute)    var $imgs = this.find('img[src!=""]');    // if there's no images, just return an already resolved promise    if (!$imgs.length) {return $.Deferred().resolve().promise();}    // for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)    var dfds = [];      $imgs.each(function(){        var dfd = $.Deferred();        dfds.push(dfd);        var img = new Image();        img.onload = function(){dfd.resolve();}        img.onerror = function(){dfd.resolve();}        img.src = this.src;    });    // return a master promise object which will resolve when all the deferred objects have resolved    // IE - when all the images are loaded    return $.when.apply($,dfds);}

然后,您可以使用如下所示的内容:

$.ajax({    cache: false,    url: 'ajax/content.php',    success: function(data) {        $('#divajax').html(data).imagesLoaded().then(function(){ // do stuff after images are loaded here        });    }});

希望这对某人有帮助。

请注意,使用上面的代码,如果其中一个图像错误(例如,由于URL错误),则应许将得到解决,并且错误将被忽略。这可能就是您想要的,但是,根据您的情况,如果图像无法加载,您可能想放弃正在做的任何事情。在这种情况下,您可以按以下方式替换onerror行:

img.onerror = function(){dfd.reject();}

并捕获如下错误:

$('#divajax').html(data).imagesLoaded().done(function(){    // do stuff after all images are loaded successfully here}).fail(function(){    // do stuff if any one of the images fails to load});


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/469268.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号