简体   繁体   English

如何加快网站背景图片的加载速度?

[英]How can I speed up the loading of the background image for my website?

I am trying to improve the performance of my website .我正在努力提高我网站的性能。 In the Chrome DevTools, I see that the request for bg2.jpg is being delayed in starting its download.在 Chrome DevTools 中,我看到对 bg2.jpg 的请求在开始下载时被延迟。 Chrome DevTools 网络瀑布

I figure this is happening because I am using JavaScript to generate the URL and set it as a background image in CSS and the Chrome browser is deprioritizing the script tag containing this code.我认为这是因为我使用 JavaScript 生成 URL 并将其设置为 CSS 中的背景图像,而 Chrome 浏览器正在降低包含此代码的脚本标记的优先级。

let bgImgName = "bg" + Math.floor(Math.random() * 5);
...
document.documentElement.style.setProperty("--bgUrl", `url(img/${bgImgName}.jpg)`);

My thought is to preload the image using, <link rel="preload" href="img/bg2.jpg" as="image"> in the HTML.我的想法是预加载使用,图像<link rel="preload" href="img/bg2.jpg" as="image">中的HTML。 My problem is that I have to hardcode the URL for this to work (because my server only runs apache and does not have a true server-side language).我的问题是我必须硬编码 URL 才能工作(因为我的服务器只运行 apache 而没有真正的服务器端语言)。 My server (host with GoDaddy on a Linux shared host) does give me access to the .htaccess file and there might be a way to use Server Side Includes to inject the random number, but I have not found a way to do this.我的服务器(在 Linux 共享主机上使用 GoDaddy 的主机)确实让我可以访问 .htaccess 文件,并且可能有一种方法可以使用服务器端包含来注入随机数,但我还没有找到一种方法来做到这一点。

Is there a way to do it this way, or a different way to solve this problem?有没有办法做到这一点,或者有不同的方法来解决这个问题?

Update: Looks like I cannot use Server Side Includes.更新:看起来我不能使用服务器端包含。 I forgot that I gzip the HTML files before I upload them to the server so that there is a performance boost of serving the compressed static files right from the disk.我忘记在将 HTML 文件上传到服务器之前对它们进行 gzip 压缩,以便直接从磁盘提供压缩静态文件的性能提升。

Is there a way I can add a random number in the .htaccess file that is passed to the browser?有没有办法可以在传递给浏览器的 .htaccess 文件中添加一个随机数?

Since you have 5 random images, an easy way is to use CSS and make them background of any element with 0 size.由于您有 5 张随机图像,一个简单的方法是使用 CSS 并将它们设为任何大小为0元素的背景。 This will force the browser to load the image before reaching the JS script.这将强制浏览器在到达 JS 脚本之前加载图像。 Of course, the CSS need to be loaded before your JS and as soon as possible.当然,CSS 需要在你的 JS 之前加载并尽快加载。

So your code can be something like this:所以你的代码可以是这样的:

html {
  background-image:
    url("img/bg1.jpg"),
    url("img/bg2.jpg"),
    url("img/bg3.jpg"),
    url("img/bg4.jpg"),
    url("img/bg5.jpg");
  background-size:0 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM