简体   繁体   English

在AJAX响应加载完所有图像后显示div

[英]Show div once all images are loaded following AJAX response

Before I start on this, I really want to avoid using Jquery for reasons I won't go into, so please don't advise me to, as that is not what I am looking for. 在开始此操作之前,我真的想避免使用Jquery,原因是我不打算这样做,所以请不要建议我这样做,因为这不是我想要的。

I have web page in development which sends multiple ajax requests off and each one returns a lump of html containing an outer div containing inner divs and images. 我有一个正在开发中的网页,它发送多个ajax请求,每个请求都返回一个html块,其中包含一个包含内部div和图像的外部div。 The issue I have is the html returned is showing on the screen before the images within it are finished rendering, giving me a couple of seconds of broken images, which looks amateur. 我遇到的问题是返回的html在其中的图像完成渲染之前显示在屏幕上,这给了我几秒钟的破碎图像,看起来很业余。

Is there a way that anyone knows of (without JQuery), that I can programmatically inspect everything within the outer div (possibly using recursion as there are several embedded inner divs etc) and only show the div if all the contents have finished rendering? 有没有人知道(没有JQuery)的方法,我可以以编程方式检查外部div中的所有内容(可能使用递归,因为有多个嵌入式内部div等),并且仅在所有内容都已完成渲染时才显示div?

 var fakeResponse = "<div class=\\"outer\\"><div class=\\"inner\\"><img src=\\"http://upload.wikimedia.org/wikipedia/commons/5/58/Sunset_2007-1.jpg\\" /></div></div>", fakeDiv = document.createElement("div"), // here we will store the response, so we can use the .getXXX functions images, imagesReady = 0, i, length, callback = function() { // this will help us to determine if all images have been loaded and to show the response if the preloading has finished imagesReady++; if (imagesReady == length) { document.body.appendChild(fakeDiv.firstChild); } }; fakeDiv.innerHTML = fakeResponse; // let the browser convert the response into dom nodes images = fakeDiv.getElementsByTagName("img"); // get all the included images for (i = 0, length = images.length; i < length; i++) { // then preload each picture var img = new Image(); img.onerror = callback; // add event handlers to determine the state of processing img.onload = callback; img.src = images[i].src; // init the actual loading } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM