About
Parsing of HTML files happens synchronously and incrementally, meaning that the parser can pause at any point to let scripts run. It does mean that authors need to be careful to avoid hooking event handlers after the events could have possibly fired.
There are two techniques for doing this reliably:
- or create the element and add the event handlers in the same script. This solution is safe because scripts are run to completion before further events can fire.
Articles Related
Example
img elements and the load event.
The event could fire as soon as the element has been parsed, especially if the image has already been cached (which is common).
Here, the author uses the onload handler on an img element to catch the load event:
<img src="games.png" alt="Games" onload="gamesLogoHasLoaded(event)">
If the element is being added by script, then so long as the event handlers are added in the same script, the event will still not be missed:
<script>
var img = new Image();
img.src = 'games.png';
img.alt = 'Games';
img.onload = gamesLogoHasLoaded;
// img.addEventListener('load', gamesLogoHasLoaded, false); // would work also
</script>
However, if the author first created the img element and then in a separate script added the event listeners, there's a chance that the load event would be fired in between, leading it to be missed:
Do not use this style, it has a Concurrency - Race Condition (Concurrency Problem)!
<img id="games" src="games.png" alt="Games">
<!-- the 'load' event might fire here while the parser is taking a
break, in which case you will not see it! -->
<script>
var img = document.getElementById('games');
img.onload = gamesLogoHasLoaded; // might never fire!
</script>