I'm using multiple image preloading with JavaScript, and I'm assigning some style attributes to each of them, which is possible since these are HTML Images elements. I use the Promise technique, that I found here on StackOverflow:
function preloadImages(srcs) {
function loadImage(imgToLoad) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = img.onabort = function() {
reject(imgToLoad.src);
};
img.className = 'testimg'; //Test to see if I can retrieve img
img.src = imgToLoad.src;
img.style.top = imgToLoad.top;
});
}
var promises = [];
for (var i = 0; i < srcs.length; i++) {
promises.push(loadImage(srcs[i]));
}
return Promise.all(promises);
}
An example of the value of "srcs":
srcs[0].top = '15%';
srcs[0].src = 'img/myImage1.jpg';
srcs[1].top = '24%';
srcs[1].src = 'img/myImage2.jpg';
The preloading part works perfectly, and I'm able to get all of the preloaded images at the end of the process, seeing that the style attributes have been applied, as following:
preloadImages(imgToLoad).then(function(imgs) {
// all images are loaded now and in the array imgs
console.log(imgs); // This works
console.log(document.getElementsByClassName('testimg')); //This doesn't
}, function(errImg) {
// at least one image failed to load
console.log('error in loading images.');
});
However, later in my code, I would like to take some of the elements from the array of preloaded images, so I can append them without having to precise the style attributes.
By that, I mean something more than only .append('aSrcThatHasBeenPreloaded');
. I want to keep the class and style attributes I defined during the preload.
Is that even possible? And if so, how should I proceed?
I tried document.getElementsByClassName('myPreloadedClass')
but it returns an empty result, which means the preloaded images are not part of the DOM (which makes perfect sense).
Thank you for your help.