Problem with onload event

Asked

Viewed 452 times

3

I’d like to ask someone who understands pure javascript, why this is happening.

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

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

image appears when loading.

But if I do so, 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, guys? There’s some solution to this?

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

Thanks to all who help, see you later!

1 answer

4


There are some limitations related to the problem you describe, inconsistencies between browsers and the fact that HTML starts caching the image even before Javascript is read and joins this addEventListener.

By these alternatives are:

  • go 100% HTML
  • go 100% Javascript

With HTML as you mentioned, add the attribute onload and it’s gonna be okay:

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

With Javascript you can use the HTML 5 API new Image(); and replace the element. So you have control over the event onload 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: https://jsfiddle.net/4mapbkq7/

Things to take into account:

  • using HTML is better for SEO and cases you want Google to index the page
  • change the src of a img can cause changes in page layout if dimensions are not closed.
  • using the Javascript version it will break event headphones that may be associated with img original that will be removed, uses delegation to avoid bugs
  • loading the image via Javascript speeds up the page loading as the browser will give the page as complete earlier.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.