Events happening before we can listen them in JS?

236 Views Asked by At

I have an image event handling code below as

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Promise DEMO</title>    
</head>
<body>
<img src="someImagePath.jpg" class="img-1"/>
</body>
</html>

JavaScript

var img1 = document.querySelector('.img-1');

img1.addEventListener('load', function() {
  // woo yey image loaded
});

img1.addEventListener('error', function() {
  // argh everything's broken
});

What would be the case, where it will be possible that the events happen before I start listening to them?

Aim is to understand why I should use promises.

1

There are 1 best solutions below

0
On

Generally speaking, events (including DOM changes) in javascript are completely async, thus the point in time when you bind a listener to an object can happen before or after the event is happening.

Simple example:

  1. Browser starts building up the document
  2. Image tag found and placed in the DOM flow
  3. Image source downloading in the background
  4. Javascript found, starting to execute
  5. Image source loaded
  6. Javascript event listener binding found
  7. The image already loaded, no more load event to listen to

A more detailed explanation about these scenarios and how using promises can solve them can be found at the link below:

http://www.html5rocks.com/en/tutorials/es6/promises/