2

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.

Mozak
  • 2,738
  • 4
  • 30
  • 49
  • The image could be loaded before this code. We have no idea when you run it. – zerkms Dec 24 '13 at 05:41
  • @zerkms ok, so it may be possible that the image has already loaded and my JS code is still in the process of adding the event handlers..Apologies if this is a typo.. – Mozak Dec 24 '13 at 05:54
  • you still haven't explained how, where and when your js is called. – zerkms Dec 24 '13 at 06:39
  • It does indeed sound like the image is cached, in which case the load event will usually fire on the image as it is read by the browser (this is, however, browser dependent, but most do it this way) and if your JS is at the bottom of the page, it won't see this event. You can easily test whether this is the case by clearing your browser cache. You can find a jquery [solution here](http://stackoverflow.com/a/3590761/881250). – uɥƃnɐʌuop Dec 24 '13 at 08:41

1 Answers1

1

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/