jQuery - how to measure the load time of an image in the background

Asked

Viewed 218 times

-1

How to run code when an image used as background is loaded?

I tried to :

$ ('#IDdaImagem').on('load', function () {
     / / 'Código parágrafo CARREGAR uma page / Conteúdo' 
}) 

and does not work the image continues to be loaded after...

is a background image, and use a jQuery plugin to open in other resolutions, the backstretch, it uses a div with backstretch class, as I load this background image with 2mb before the content of the site?

I tested this and it works, but not in the element that I will give show, only in Alert.

<script>
$('.backstretch img').load(function() {
    alert('done loading image');
    $("#corpo").show();
});
</script>

This doesn’t work:

<script>
$ ('#IDdaImagem').on('load', function () { // no space
      $("#corpo").show();
}) 
</script>

This works:

<script>
$ ('#IDdaImagem').on('load', function () { // no space
      alert ('Test');
}) 
</script>
  • How is the element #corpo before the script runs? If your style is like display: none shall function; if visibility: hidden, no (because they are different things).

  • Another thing: I saw your question "Load page only when image is loaded", I don’t know if this can be considered a duplicate of it or not. I’ll let the community decide...

1 answer

1

I don’t think it’s possible to measure the load of a background. One idea you can test is to upload the image to a <img> that will never be used in the DOM. It will be used as a "test" to know when the image is loaded into the computer cache and then available to be used as background.

I made this code:

var scriptLido = new Date().getTime();
var imagemFalsa = $('<img />');

imagemFalsa.on('load', function () {
    var imagemCarregada = new Date().getTime();
    console.log(imagemCarregada - scriptLido, 'Imagem carregada');
});

imagemFalsa.attr("src", "http://scienceblogs.com/startswithabang/files/2013/05/chemical_composition_universe.jpeg");


$('#imagemEscondida').ready(function () {
    var domReady = new Date().getTime();
    console.log(domReady - scriptLido, 'domReady');
});

And gave me this result:

2 "domReady"
330 "Loaded image"

This means that the image was loaded 328 milliseconds after the Domready event, which in turn was 2 ms undone from the beginning of the code. On a real page these numbers will perhaps be bigger since my script is very small.

Interestingly, and as confirmation, when I loaded the page again, already with the cached image, the load ("Image loaded" ) came only 6 ms later.

So I think you can use this trick.

Example

Browser other questions tagged

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