Pergunta

I have an application which the speed of loading an image is really important for the user experience.

This is what I can see in the "net" tab from firefox. The image is the intro-...:

enter image description here

First I thought that it was being loaded later because it is only described on the CSS file (as a background-image). So I tried to add a image tag on the start of my HTML body with style="display: none".

However, to surprise, the point where the image starts being loaded didn't change, even if the image was not hidden.

Update

Thanks to @LOLKFC answer I learned about image preload "jargon". I read about it and I tried many tatics: create an image (with jquery or only the object), use css background with big negative positions, use jquery get and many others. The only acceptable solution by being fast enought I found was this one:

xhr = new XMLHttpRequest()
xhr.open('GET', '/assets/intro-24108df7e2b69baf419efb3a4da9d994.jpg', true);
xhr.send('');

however, it seems that the image is loaded again when parsing the css file, and the image still takes time to render.

I'm sending Expires = Thu, 31 Dec 2037 23:55:55 GMT on my HTTP header, but it seems that even though, the image is loaded all again for the style, not effectively pre-loading the image.

enter image description here

So right now I'm doing the following:

  xhr = new XMLHttpRequest()
  xhr.open('GET', '/assets/intro.jpg', false);
  xhr.send(null);
  var image = btoa(unescape(encodeURIComponent(xhr.responseText)));

and the following line to set the image as background is not working:

     document.getElementById('intro').style.background = 'url(data:image/jpeg;base64,'+image+') no-repeat bottom center scroll';

How can I fix this line?

Foi útil?

Solução

With Javascript, you can do something like this http://jsfiddle.net/HU7BR/, with the script in the beginning of the html:

// 1. One way you could make performance better is by pre-caching the image:
(new Image).src = "http://www.massachusetts-prenuptial-agreements.com/wp-content/uploads/2011/05/Sunset-1.jpg"; // pre-cached!


// 2. Another thing you could do is make an image element with the source of your big file and when it loads, dynamically make the background of your body that picture:
var img = document.createElement('img');
img.style.display = "none";
img.src = "http://www.massachusetts-prenuptial-agreements.com/wp-content/uploads/2011/05/Sunset-1.jpg";

img.onload = function() { // when the image loads, do this
    document.body.style.background = "url(http://www.massachusetts-prenuptial-agreements.com/wp-content/uploads/2011/05/Sunset-1.jpg)";
};
// that way, the image will be fully loaded before the body gets its new background image


// now delete!:
img = null;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top