Skip to content
Advertisement

How to know if all onload Events already fired?

This question is a more specific and a superset of this question: How to know if window “load” event was fired already .

Use Case

So I have this use case where I need to make a lazy loaded CSS-only slideshow of pictures and for that I realized it thru onload Events which fire with the slide number, which fires after a delay only when the picture finished loading the picture in question. The problem is that the suggested answer shows 'complete' after the first onload Event fired, which is not fitting for me. So my question is – how do I detect whether all onload Events already fired?

The problem

All my slides go thru and afterwards the slideshow misbehaves. That’s why I need to detect that condition so that I can control my slide behaviour after the fact and so fix this problem.

StackBlitz Link

https://stackblitz.com/edit/js-fsymew

GitHub Link

https://github.com/munchkindev/js-fsymew

My HTML:

JavaScript

JS:

JavaScript

Try 2

HTML:

JavaScript

JS:

JavaScript

Advertisement

Answer

I would use promises to listen to image load events, this way you can wait for all the promises to complete before initiating your carousel.

For example, if you had the below html:

JavaScript

You could wait for all these to load with something like:

JavaScript

I’ve created working example for you below. You’ll notice that before all the images have loaded the carousel will display a red border. Once loaded the border color changes to green.

JavaScript
JavaScript
JavaScript

Or you can view it on JSFiddle here: https://jsfiddle.net/thelevicole/b13gpyfd/2/


Edit

Below is updated example of how to lazy load slide images only when the slide is in view instead of waiting for all images to load on init.

https://jsfiddle.net/thelevicole/b13gpyfd/3/

JavaScript
JavaScript
JavaScript

I’ve added a hook mechanism to allow callbacks to run everytime the slide changes carousel.addAction('goto', (slide, index) => { ... });

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement