【问题标题】:Start load image earlier on a page request在页面请求上更早开始加载图像
【发布时间】:2024-05-23 20:15:01
【问题描述】:

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

这是我在 Firefox 的“网络”选项卡中看到的内容。图片是intro-...

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

然而,令人惊讶的是,图像开始加载的点并没有改变,即使图像没有隐藏。

更新

感谢@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,但似乎即使该样式再次加载了图像,也没有有效地预加载图像。

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

  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';

如何修复这条线?

【问题讨论】:

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


    【解决方案1】:

    使用 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;
    

    【讨论】:

    • 谢谢,我试过这个和很多其他我可以用谷歌搜索的选项,但同样的东西显示在 firefox 网络标签上:(