Does It Consider Recursion If I Call Onload Event On The Funcion Which I'm Inside?
Solution 1:
My questions is:
1) When I attach an event handler "loadImage" to an image, does it consider recursion because I'm doing it inside this function?
No, the JavaScript at Question does not perform a "recursion". You are scheduling a possible function call, not return
ing a value from a function call.
See
Solution 2:
Now that we've established that your code is not recursive, let me show you a technique to make your lazy-loading occur even faster.
Right now, because of how you chain your load
events, it will load each image one at a time in sequence. Using Promise.all()
, you can load all of them in parallel without having to keep count of them like this:
functionlazyCss(gallery) {
var images = gallery.slider.find('[data-lazy-image]')
var promises = images.toArray().map(img => {
var link = img.dataset.lazyImagedelete img.dataset.lazyImage
img.style.backgroundImage = `url(${link})`returnnewPromise((resolve, reject) => {
var image = newImage()
image.onload = resolve
// we don't want to abort or hang lazy loading if an image fails// so we attach resolve to onerror to prevent issues just in case
image.onerror = resolve
image.src = link
})
})
returnPromise.all(promises)
}
Now, if you have some other code that can't run until all the images are finished loading, you can call the function like this:
lazyCss(myGallery).then(() => {
// dependent code goes here// won't run until all images in gallery loaded
})
Post a Comment for "Does It Consider Recursion If I Call Onload Event On The Funcion Which I'm Inside?"