2

首先,一些背景信息:

大约 1999 年的 HTTP 1.1 规范建议浏览器和服务器将对同一主机名的并行请求限制为两个。(更多

如果您继续阅读那篇文章,作者建议通过让多个子域都指向同一事物来“欺骗”浏览器。

如果我要从两个单独的子域(两个不同的主机名)提供我的图像,那么浏览器将最多并行下载 4 个图像(每个主机名 2 个)。

鉴于此,我现在可以在两个子域之间平均分配请求以优化页面下载速度,如下所示:

<img src="http://subdomain1.example.com/img1.jpg" />
<img src="http://subdomain2.example.com/img2.jpg" />
<img src="http://subdomain1.example.com/img3.jpg" />
<img src="http://subdomain2.example.com/img4.jpg" />

这将需要我手动浏览适当的文件并更改每个图像的“src”。


我正在寻找一种更简单/可重用的解决方案,该解决方案不涉及对 HTML 的可见更改。

我有个主意:

  1. [example.com] 上的所有类似图像的 URL 都被重定向(通过 .htaccess)到 [example.com/imghandler.php]
  2. imghandler.php 重定向到 subdomain1 或 subdomain2 - 随机选择。

为了显示:

# Request from browser:
>> http://example.com/dir/image.jpg

# Rewritten to:
>> http://example.com/imghandler.php?location=%2Fdir%2Fimage.jpg

# *Redirects* to either:
    1:
        >> http://subdomain1.example.com/dir/image.jpg
           (this is where the browser ends up getting the image from)
    2:
        >> http://subdomain2.example.com/dir/image.jpg
           (this is where the browser ends up getting the image from)

我有两个问题:

  1. 从理论的角度来看,这行得通吗?
  2. 有没有更好的方法来完成我想要的?
4

3 回答 3

5

使用此类策略要记住的一件事是,您希望将对同一文件的请求定向到同一服务器。请求以下内容并没有多大好处:

http://subdomain1.example.com/img1.jpg
http://subdomain2.example.com/img2.jpg
http://subdomain1.example.com/img3.jpg
http://subdomain2.example.com/img4.jpg

然后在一页上:

http://subdomain2.example.com/img1.jpg
http://subdomain1.example.com/img2.jpg
http://subdomain2.example.com/img3.jpg
http://subdomain1.example.com/img4.jpg

在下。

我们在这里使用的技巧是散列文件名(C# 中的 GetHashCode)并使用它来选择存储桶:

var serverNumber = image.GetHashCode() % serverCount;

这确保了对同一图像的进一步请求是从浏览器的缓存而不是由不同的服务器提供的。

于 2009-06-13T00:20:42.797 回答
0

您最好将所有图像都放在一台服务器上,而不是对每个图像进行 2 个请求。

如果您有动态页面内容(即看起来您正在使用 php),您可以通过创建一个执行相同操作的函数来获得相同的效果并直接在 html 中对子域进行编码。您的图像标签可能如下所示:

<img src="<?php echo image_root(); ?>/dir/image.jpg">

您应该能够使用体面的编辑器和一些正则表达式搜索和替换将这种更改全局应用于您的站点。

于 2009-06-12T23:49:11.530 回答
0
  1. 是的。它会起作用的。但是您最终会收到两倍的请求,仍然会阻碍第一个请求以通过 2×2 主域获得可能的重定向。

  2. 在图像实际开始加载之前,您可以尝试使用 JavaScript(也称为 jQuery)在 DOM 的就绪事件中快速更改图像的来源。您希望使用一致的方法来计算要使用的子域选项,以便将来引用相同图像的页面会导致对相同子域选择的更改。

于 2009-06-13T01:18:14.767 回答