简体   繁体   中英

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.

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. 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.

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?

 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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