在页面请求之前开始加载图像

时间:2014-05-02 15:03:16

标签: html ajax performance ruby-on-rails-4 http-headers

我有一个应用程序,加载图像的速度对用户体验非常重要。

这是我在firefox的“net”标签中可以看到的。图像是intro-...

enter image description here

首先我认为它稍后被加载,因为它只在CSS文件中描述(作为background-image)。所以我尝试使用style="display: none"在我的HTML正文的开头添加一个图片代码。

然而,令人惊讶的是,即使图像未被隐藏,图像开始加载的点也不会改变。

更新

感谢@LOLKFC回答我了解了图片预载“行话”。我读到了它并且我尝试了许多破坏:创建一个图像(使用jquery或只有对象),使用具有大负面位置的css背景,使用jquery get和许多其他。我找到的唯一可接受的解决方案就是这个:

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

但是,在解析css文件时似乎再次加载了图像,并且图像仍然需要时间来渲染。

我正在我的HTTP标头上发送Expires = Thu, 31 Dec 2037 23:55:55 GMT,但似乎即使图像再次加载到样式中,也没有有效地预加载图像。

enter image description here

所以现在我正在做以下事情:

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

以及将图像设置为背景的以下行无效:

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

我该如何修理这条线?

1 个答案:

答案 0 :(得分:2)

使用Javascript,您可以使用html开头的脚本执行此类http://jsfiddle.net/HU7BR/之类的操作:

// 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;
相关问题