Problem with onload event

3

I would like to ask someone who is knowledgeable in pure javascript, why this is happening.

I have a code that should only show the image when it is loaded (onload), but the function only fires when I wrap the onload directly in the img tag, when I put it in a block / javascript file it does not work ...

If I do: <img id="imagem" src="linkDaImagem" onload="this.style.display = 'block'" />

The image appears when loading.

But if I do this, in a script block or external file, it does not work:

document.getElementById('imagem').addEventListener("load", function(){
      this.style.display = 'block';       
});

Why does this happen, people? Do you have a solution for this?

I know Jquery is possible, but I ask for the solution in pure js, since I am learning it, and I have this doubt ...

Thanks to all who help, even more!

    
asked by anonymous 04.10.2016 / 00:20

1 answer

4

There are some limitations related to the problem you are describing, inconsistencies between browsers, and the fact that HTML begins to load the cached image even before JavaScript is read and adds that addEventListener .

These alternatives are:

  • go 100% HTML
  • go 100% JavaScript

With HTML is as you mentioned, add the attribute onload and the thing will go well:

onload="this.style.display = 'block'"

With JavaScript you can use the HTML API 5 new Image(); and replace the element. So you have control over the onload event in JavaScript:

var img = document.getElementById('imagem');
var el = new Image();
img.parentElement.replaceChild(el, img);
el.onload = function() {
    this.style.opacity = 1;
};
el.src = "linkDaImagem";

Example: link

Things to consider:

  • Using HTML is better for SEO and cases that you want Google to index the page
  • Changing the src of a img can cause page layout changes if the dimensions are not set.
  • Using the JavaScript version it will break headphones of events that may be associated with the original img to be removed, use delegation to avoid bugs
  • Loading the image via JavaScript speeds up page loading because the browser will give the page as complete earlier.
04.10.2016 / 01:10