jQuery - how to measure the loading time of a background image [duplicate]

-1

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

I tried:

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

and does not work the image continues to load after ...

is a background image , and I 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 on the element I'm going to give show, only on alert.

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

This does not work:

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

This works:

<script>
$ ('#IDdaImagem').on('load', function () { // no space
      alert ('Test');
}) 
</script>
    
asked by anonymous 07.04.2014 / 05:31

1 answer

1

I do not think it's possible to measure load of a background. One idea you can test is to load the image into a <img> that will never be used in the DOM. It will be used as a "test" to know when the image is loaded in the computer cache and 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 it gave me this result:

  

2 "domReady" 330 "Uploaded image"

This means that the image was loaded 328 milliseconds after the DOMReady event, which in turn was 2 ms down from the start of the code. On a serious page, these numbers are perhaps larger because my script is very small.

So I think you can use this trick.

Example

    
07.04.2014 / 10:58