优化页面加载时间

注:机翻,未校对。 本文年代久远,除了少部分不合时宜的,其他仍有借鉴意义。

Optimizing Page Load Time

优化页面加载时间

It is widely accepted that fast-loading pages improve the user experience. In recent years, many sites have started using AJAX techniques to reduce latency. Rather than round-trip through the server retrieving a completely new page with every click, often the browser can either alter the layout of the page instantly or fetch a small amount of HTML, XML, or javascript from the server and alter the existing page. In either case, this significantly decreases the amount of time between a user click and the browser finishing rendering the new content.

人们普遍认为,快速加载的页面可以改善用户体验。近年来,许多站点已开始使用 AJAX 技术来减少延迟。浏览器通常可以立即更改页面的布局,或者从服务器获取少量的 HTML、XML 或 javascript 并更改现有页面,而不是在每次单击时在服务器之间往返检索一个全新的页面。无论哪种情况,这都会显著缩短用户单击和浏览器完成呈现新内容之间的时间。

However, for many sites that reference dozens of external objects, the majority of the page load time is spent in separate HTTP requests for images, javascript, and stylesheets. AJAX probably could help, but speeding up or eliminating these separate HTTP requests might help more, yet there isn't a common body of knowledge about how to do so.

但是,对于许多引用数十个外部对象的网站,大部分页面加载时间都花在对图像、javascript 和样式表的单独 HTTP 请求中。AJAX 可能会有所帮助,但加速或消除这些单独的 HTTP 请求可能会有所帮助,但关于如何做到这一点,还没有一个共同的知识体系。

While working on optimizing page load times for a high-profile AJAX application, I had a chance to investigate how much I could reduce latency due to external objects. Specifically, I looked into how the HTTP client implementation in common browsers and characteristics of common Internet connections affect page load time for pages with many small objects.

在为一个备受瞩目的 AJAX 应用程序优化页面加载时间时,我有机会研究一下由于外部对象导致的延迟可以减少多少。具体来说,我研究了常见浏览器中的 HTTP 客户端实现和常见 Internet 连接的特征如何影响具有许多小对象的页面的页面加载时间。

I found a few things to be interesting:

我发现有几件事很有趣:

  • IE, Firefox, and Safari ship with HTTP pipelining disabled by default; Opera is the only browser I know of that enables it. No pipelining means each request has to be answered and its connection freed up before the next request can be sent. This incurs average extra latency of the round-trip (ping) time to the user divided by the number of connections allowed. Or if your server has HTTP keepalives disabled, doing another TCP three-way handshake adds another round trip, doubling this latency.
    IE、Firefox 和 Safari 默认禁用 HTTP 流水线;Opera 是我所知道的唯一支持它的浏览器。没有流水线意味着在发送下一个请求之前,必须应答每个请求并释放其连接。这会导致用户的平均额外往返 (ping) 时间除以允许的连接数。或者,如果您的服务器禁用了 HTTP keepalives,则再执行一次 TCP 三向握手会增加另一个往返行程,从而使此延迟加倍。
  • By default, IE allows only two outstanding connections per hostname when talking to HTTP/1.1 servers or eight-ish outstanding connections total. Firefox has similar limits. Using up to four hostnames instead of one will give you more connections. (IP addresses don't matter; the hostnames can all point to the same IP.)
    默认情况下,IE 在与 HTTP/1.1 服务器通信时,每个主机名只允许两个未完成的连接,或者总共允许八个未完成的连接。Firefox也有类似的限制。使用最多四个主机名而不是一个主机名将为您提供更多连接。(IP 地址无关紧要;主机名都可以指向同一个 IP。
  • Most DSL or cable Internet connections have asymmetric bandwidth, at rates like 1.5Mbit down/128Kbit up, 6Mbit down/512Kbit up, etc. Ratios of download to upload bandwidth are commonly in the 5:1 to 20:1 range. This means that for your users, a request takes the same amount of time to send as it takes to receive an object of 5 to 20 times the request size. Requests are commonly around 500 bytes, so this should significantly impact objects that are smaller than maybe 2.5k to 10k. This means that serving small objects might mean the page load is bottlenecked on the users' upload bandwidth, as strange as that may sound.
    大多数 DSL 或有线互联网连接具有非对称带宽,速率为 1.5Mbit down/128Kbitup、6Mbit down/512Kbit up 等。下载与上传带宽的比率通常在 5:1 到 20:1 之间。这意味着,对于用户来说,发送请求所需的时间与接收请求大小 5 到 20 倍的对象所需的时间相同。请求通常约为 500 字节,因此这应该会显着影响小于 2.5k 到 10k 的对象。这意味着提供小对象可能意味着页面加载在用户的上传带宽上受到瓶颈,这听起来很奇怪。

Using these, I came up with a model to guesstimate the effective bandwidth of users of various flavors of network connections when loading various object sizes. It assumes that each HTTP request is 500 bytes and that the HTTP reply includes 500 bytes of headers in addition to the object requested. It is simplistic and only covers connection limits and asymmetric bandwidth, and doesn't account for the TCP handshake of the first request of a persistent (keepalive) connection, which is amortized when requesting many objects from the same connection. Note that this is best-case effective bandwidth and doesn't include other limitations like TCP slow-start, packet loss, etc. The results are interesting enough to suggest avenues of exploration but are no substitute for actually measuring the difference with real browsers.

利用这些,我提出了一个模型来猜测各种类型的网络连接的用户在加载各种对象大小时的有效带宽。它假定每个 HTTP 请求为 500 字节,并且 HTTP 回复除了请求的对象外还包括 500 字节的标头。它很简单,仅涵盖连接限制和非对称带宽,并且不考虑持久 (keepalive) 连接的第一个请求的 TCP 握手,当从同一连接请求多个对象时,该握手会摊销。请注意,这是最佳情况下的有效带宽,不包括其他限制,如 TCP 启动缓慢、数据包丢失等。结果足够有趣,可以提出探索的途径,但不能替代实际测量与真实浏览器的差异。

To show the effect of keepalives and multiple hostnames, I simulated a user on net offering 1.5Mbit down/384Kbit up who is 100ms away with 0% packet loss. This roughly corresponds to medium-speed ADSL on the other side of the U.S. from your servers. Shown here is the effective bandwidth while loading a page with many objects of a given size, with effective bandwidth defined as total object bytes received divided by the time to receive them:

为了显示 keepalive 和多个主机名的效果,我模拟了一个网络用户,提供 1.5Mbit 的下行/384Kbit 的上行,该用户距离 100 毫秒,数据包丢失率为 0%。这大致相当于美国另一端的中速ADSL。此处显示的是加载包含许多给定大小的对象的页面时的有效带宽,有效带宽定义为接收的总对象字节数除以接收它们的时间:

[1.5megabit 100ms graph]

Interesting things to note:

需要注意的有趣事项:

  • For objects of relatively small size (the left-hand portion of the graph), you can see from the empty space above the plotted line how little of the user's downstream bandwidth is being used, even though the browser is requesting objects as fast as it can. This user has to be requesting objects larger than 100k before he's mostly filling his available downstream bandwidth.
    对于尺寸相对较小的对象(图形的左侧部分),您可以从绘制线上方的空白处看到用户使用的下行带宽有多少,即使浏览器正在尽可能快地请求对象。此用户必须请求大于 100k 的对象,然后才能大部分填充其可用的下行带宽。
  • For objects under roughly 8k in size, you can double his effective bandwidth by turning keepalives on and spreading the requests over four hostnames. This is a huge win.
    对于大小小于 8k 的对象,您可以通过打开 keepalive 并将请求分布在四个主机名上来将他的有效带宽增加一倍。这是一个巨大的胜利。
  • If the user were to enable pipelining in his browser (such as setting Firefox's network.http.pipelining in about:config), the number of hostnames we use wouldn't matter, and he'd make even more effective use of his available bandwidth. But we can't control that server-side.
    如果用户在他的浏览器中启用流水线(例如在 about:config 中设置 Firefox 的 network.http.pipelining),我们使用的主机名数量将无关紧要,并且他会更有效地利用他的可用带宽。但是我们无法控制服务器端。

Perhaps more clearly, the following is a graph of how much faster pages could load for an assortment of common access speeds and latencies with many external objects spread over four hostnames and keepalives enabled. Baseline (0%) is one hostname and keepalives disabled.

也许更清楚的是,下图显示了在各种常见访问速度和延迟下,许多外部对象分布在四个主机名上并启用了 keepalive,页面加载速度可以提高多少。基线 (0%) 是一个主机名,并禁用了 keepalives。

[Speedup of 4 hostnames and keepalives on]

Interesting things from that graph:

该图中有趣的事情:

  • If you load many objects smaller than 10k, both local users and ones on the other side of the world could see substantial improvement from enabling keepalives and spreading requests over 4 hostnames.
    如果您加载许多小于 10k 的对象,则本地用户和世界另一端的用户都可以通过启用 keepalive 和将请求分散到 4 个主机名中看到实质性的改进。
  • There is a much greater improvement for users further away.
    对于更远的用户来说,有更大的改进。
  • This will matter more as access speeds increase. The user on 100meg ethernet only 20ms away from the server saw the biggest improvement.
    随着访问速度的提高,这将变得更加重要。距离服务器仅 20 毫秒的 100meg 以太网上的用户看到了最大的改进。

One more thing I examined was the effect of request size on effective bandwidth. The above graphs assumed 500 byte requests and 500 bytes of reply headers in addition to the object contents. How does changing that affect performance of our 1.5Mbit down/384Kbit up and 100ms away user, assuming we're already using four hostnames and keepalives?

我研究的另一件事是请求大小对有效带宽的影响。上图假设除了对象内容外,还有 500 字节的请求和 500 字节的回复标头。假设我们已经使用了四个主机名和 keepalive,更改它如何影响我们的 1.5Mbit down/384Kbit up 和 100ms away 用户的性能?

[Effective bandwidth at various request sizes]

This shows that at small object sizes, we're bottlenecked on the upstream bandwidth. The browser sending larger requests (such as ones laden with lots of cookies) seems to slow the requests down by 40% worst-case for this user.

这表明,在较小的对象尺寸下,我们在上行带宽上遇到了瓶颈。对于该用户来说,发送较大请求(例如充满大量 cookie 的请求)的浏览器似乎会将请求速度减慢 40%。

As I've said, these graphs are based on a simulation and don't account for a number of real-world factors. But I've unscientifically verified the results with real browsers on real net and believe them to be a useful gauge. I'd like to find the time and resources to reproduce these using real data collected from real browsers over a range of object sizes, access speeds, and latencies.

正如我所说,这些图表是基于模拟的,没有考虑许多现实世界的因素。但是我已经在真实网络上用真实的浏览器不科学地验证了结果,并相信它们是一个有用的衡量标准。我想找到时间和资源来使用从真实浏览器收集的真实数据来重现这些数据,这些数据涉及各种对象大小、访问速度和延迟。

Measuring the effective bandwidth of your users

衡量用户的有效带宽

You can measure the effective bandwidth of your users on your site relatively easily, and if the effective bandwidth of users viewing your pages is substantially below their available downstream bandwidth, it might be worth attempting to improve this.

您可以相对容易地测量网站上用户的有效带宽,如果用户查看您页面的有效带宽大大低于其可用的下行带宽,则可能值得尝试改进这一点。

Before giving the browser any external object references (<img src="...">, <link rel="stylesheet" href="...">, <script src="...">, etc), record the current time. After the page load is done, subtract the time you began, and include that time in the URL of an image you reference off of your server.

在向浏览器提供任何外部对象引用(<img src="...">、<link rel="stylesheet" href="...">、<script src="...">等)之前,请记录当前时间。页面加载完成后,减去开始的时间,并将该时间包含在从服务器引用的图像的 URL 中。

Sample javascript implementing this:

实现此目的的示例 javascript:

javascript 复制代码
<html>
<head>
  <title>Your Page Title</title>
  <script type="text/javascript">
    <!--
    var began_loading = (new Date()).getTime();

    function done_loading() {
      (new Image()).src = '/timer.gif?u=' + self.location + '&t=' + 
        (((new Date()).getTime() - began_loading) / 1000);
    }
    // -->
  </script>
  <!-- Reference any external JavaScript or stylesheets after the above block. -->
</head>
<body onload="done_loading()">
  <!-- Put your normal page content here. -->
</body>
</html>

This will produce web log entries of the form:

10.1.2.3 - - [28/Oct/2006:13:47:45 -0700] "GET /timer.gif?u=http://example.com/page.html\&t=0.971 HTTP/1.1" 200 49 ...

in this case, showing that for this user, loading the rest of http://example.com/page.html took 0.971 seconds. And if you know that the combined size of everything referenced from that page is 57842 bytes, 57842 bytes * 8 bits per byte / 0.971 seconds = 476556 bits per second effective bandwidth for that page load. If this user should be getting 1.5Mbit downstream bandwidth, there is substantial room for improvement.

在本例中,显示对于此用户,加载 http://example.com/page.html 的其余部分需要 0.971 秒。如果您知道从该页面引用的所有内容的总大小为 57842 字节,则 57842 字节 * 每字节 8 位 / 0.971 秒 = 该页面加载的每秒 476556 位有效带宽。如果该用户应该获得 1.5Mbit 的下行带宽,则有很大的改进空间。

Tips to reduce your page load time

减少页面加载时间的提示

After you gather some page-load times and effective bandwidth for real users all over the world, you can experiment with changes that will improve those times. Measure the difference and keep any that offer a substantial improvement.

在为世界各地的真实用户收集一些页面加载时间和有效带宽后,您可以尝试更改以改善这些时间。衡量差异并保留任何提供实质性改进的差异。

Try some of the following:

请尝试以下一些操作:

  • Turn on HTTP keepalives for external objects. Otherwise you add an extra round-trip to do another TCP three-way handshake and slow-start for every HTTP request. If you are worried about hitting global server connection limits, set the keepalive timeout to something short, like 5-10 seconds. Also look into serving your static content from a different webserver than your dynamic content. Having thousands of connections open to a stripped down static file webserver can happen in like 10 megs of RAM total, whereas your main webserver might easily eat 10 megs of RAM per connection.

    为外部对象启用 HTTP keepalive。否则,您将添加一个额外的往返行程,以便为每个 HTTP 请求执行另一个 TCP 三向握手和慢启动。如果您担心会达到全局服务器连接限制,请将 keepalive 超时设置为较短的值,例如 5-10 秒。此外,还可以考虑从与动态内容不同的 Web 服务器提供静态内容。打开数千个连接到精简的静态文件 Web 服务器可能会总共花费 10 兆的 RAM,而您的主 Web 服务器可能很容易在每个连接消耗 10 兆的 RAM。

  • Load fewer external objects. Due to request overhead, one bigger file just loads faster than two smaller ones half its size. Figure out how to globally reference the same one or two javascript files and one or two external stylesheets instead of many; if you have more, try preprocessing them when you publish them. If your UI uses dozens of tiny GIFs all over the place, consider switching to a much cleaner CSS-based design which probably won't need so many images. Or load all of your common UI images in one request using a technique called "CSS sprites".

    加载更少的外部对象。由于请求开销,一个较大的文件的加载速度比两个较小的文件快一半。弄清楚如何全局引用相同的一个或两个 javascript 文件和一个或两个外部样式表,而不是很多;如果有更多内容,请尝试在发布时对其进行预处理。如果你的UI到处都使用了几十个小GIF,可以考虑切换到一个更干净的基于CSS的设计,这可能不需要那么多图像。或者使用称为"CSS 精灵"的技术在一个请求中加载所有常见的 UI 图像。

  • If your users regularly load a dozen or more uncached or uncacheable objects per page, consider evenly spreading those objects over four hostnames. This usually means your users can have 4x as many outstanding connections to you. Without HTTP pipelining, this results in their average request latency dropping to about 1/4 of what it was before.

    如果用户经常在每页加载十几个或更多未缓存或不可缓存的对象,请考虑将这些对象均匀分布在四个主机名上。这通常意味着您的用户可以拥有 4 倍的出色连接。如果没有 HTTP 流水线,这会导致他们的平均请求延迟下降到以前的 1/4 左右。

    When you generate a page, evenly spreading your images over four hostnames is most easily done with a hash function, like MD5. Rather than having all tags load objects from http://static.example.com/, create four hostnames (e.g. static0.example.com, static1.example.com, static2.example.com, static3.example.com) and use two bits from an MD5 of the image path to choose which of the four hosts you reference in the tag. Make sure all pages consistently reference the same hostname for the same image URL, or you'll end up defeating caching.

    当您生成页面时,使用哈希函数(如 MD5)最容易将图像均匀分布在四个主机名上。与其让所有标记从 http://static.example.com/ 加载对象,不如创建四个主机名(例如 static0.example.comstatic1.example.comstatic2.example.comstatic3.example.com),并使用映像路径的 MD5 中的两个位来选择标记中引用的四个主机中的哪一个。确保所有页面都一致地引用同一图像 URL 的相同主机名,否则您最终会失败缓存。

    Beware that each additional hostname adds the overhead of an extra DNS lookup and an extra TCP three-way handshake. If your users have pipelining enabled or a given page loads fewer than around a dozen objects, they will see no benefit from the increased concurrency and the site may actually load more slowly. The benefits only become apparent on pages with larger numbers of objects. Be sure to measure the difference seen by your users if you implement this.

    请注意,每个额外的主机名都会增加额外的 DNS 查找和额外的 TCP 三向握手的开销。如果您的用户启用了流水线,或者给定页面加载的对象少于十几个,则他们不会从增加的并发性中获得任何好处,并且站点实际上可能会加载得更慢。这些好处只有在具有大量对象的页面上才会显现出来。如果实现此功能,请务必衡量用户看到的差异。

  • Possibly the best thing you can do to speed up pages for repeat visitors is to allow static images, stylesheets, and javascript to be unconditionally cached by the browser. This won't help the first page load for a new user, but can substantially speed up subsequent ones.

    为了加快重复访问者的页面速度,您可以做的最好的事情可能是允许浏览器无条件缓存静态图像、样式表和 javascript。这无助于新用户的第一个页面加载,但可以大大加快后续页面的加载速度。

    Set an Expires header on everything you can, with a date days or even months into the future. This tells the browser it is okay to not revalidate on every request, which can add latency of at least one round-trip per object per page load for no reason.

    尽可能在所有内容上设置一个 Expires 标头,日期为未来几天甚至几个月。这告诉浏览器可以不对每个请求进行重新验证,这可能会无缘无故地增加每个对象每次页面加载至少一次往返的延迟。

    Instead of relying on the browser to revalidate its cache, if you change an object, change its URL. One simple way to do this for static objects if you have staged pushes is to have the push process create a new directory named by the build number, and teach your site to always reference objects out of the current build's base URL. (Instead of <img src="http://example.com/logo.gif"> you'd use <img src="http://example.com/build/1234/logo.gif">. When you do another build next week, all references change to <img src="http://example.com/build/1235/logo.gif">.) This also nicely solves problems with browsers sometimes caching things longer than they should -- since the URL changed, they think it is a completely different object.

    如果更改对象,请更改其 URL,而不是依赖浏览器重新验证其缓存。如果您已暂存推送,则对静态对象执行此操作的一种简单方法是让推送进程创建一个以内部版本号命名的新目录,并指示您的站点始终从当前构建的基 URL 中引用对象。(而不是<img src="https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=http%3A%2F%2Fexample.com%2Flogo.gif&pos_id=img-2sYoLTa3-1719812709803)"><img src="https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=http%3A%2F%2Fexample.com%2Fbuild%2F1234%2Flogo.gif&pos_id=img-POrM8AO2-1719812710448)">。当您下周进行另一次构建时,所有引用都将更改为 <img src="https://img-home.csdnimg.cn/images/20230724024159.png?origin_url=http%3A%2F%2Fexample.com%2Fbuild%2F1235%2Flogo.gif\&pos_id=img-JxRyZMOq-1719812711014)">。这也很好地解决了浏览器有时缓存内容的时间超过应有的时间的问题------由于 URL 发生了变化,他们认为这是一个完全不同的对象。

    If you conditionally gzip HTML, javascript, or CSS, you probably want to add a "Cache-Control: private" if you set an Expires header. This will prevent problems with caching by proxies that won't understand that your gzipped content can't be served to everyone. (The Vary header was designed to do this more elegantly, but you can't use it because of IE brokenness.)

    如果有条件地 gzip HTML、javascript 或 CSS,则在设置 Expires 标头时,可能需要添加"Cache-Control: private"。这将防止代理缓存问题,这些代理不了解您的 gzip 压缩内容无法提供给所有人。(Vary 标头旨在更优雅地执行此操作,但由于 IE 损坏,您无法使用它。

    For anything where you always serve the exact same content when given the same URL (e.g. static images), add "Cache-Control: public" to give proxies explicit permission to cache the result and serve it to different users. If a caching proxy local to the user has the content, it is likely to have much less latency than you; why not let it serve your static objects if it has them?

    对于在给定相同 URL 时始终提供完全相同内容的任何内容(例如静态图像),请添加"Cache-Control: public"以向代理提供缓存结果并将其提供给不同用户的显式权限。如果用户本地的缓存代理具有内容,则它的延迟可能比您少得多;如果它有静态对象,为什么不让它为你的静态对象服务呢?

    Avoid the use of query params in image URLs, etc. At least the Squid cache refuses to cache any URL containing a question mark by default. I've heard rumors that other things won't cache those URLs at all, but I don't have more information.

    避免在图像 URL 等中使用查询参数。至少 Squid 缓存默认拒绝缓存任何包含问号的 URL。我听说有传言说其他东西根本不会缓存这些 URL,但我没有更多信息。

  • On pages where your users are often sent the exact same content over and over, such as your home page or RSS feeds, implementing conditional GETs can substantially improve response time and save server load and bandwidth in cases where the page hasn't changed.

    在用户经常一遍又一遍地收到完全相同内容的页面(例如主页或 RSS 源)上,实现有条件的 GET 可以大大缩短响应时间,并在页面未更改的情况下节省服务器负载和带宽。

    When serving a static files (including HTML) off of disk, most webservers will generate Last-Modified and/or ETag reply headers for you and make use of the corresponding If-Modified-Since and/or If-None-Match mechanisms on requests. But as soon as you add server-side includes, dynamic templating, or have code generating your content as it is served, you are usually on your own to implement these.

    在磁盘上提供静态文件(包括 HTML)时,大多数 Web 服务器将为您生成 Last-Modified 和/或 ETag 回复标头,并在请求时使用相应的 If-Modified-Since 和/或 If-None-Match 机制。但是,一旦您添加了服务器端包含、动态模板,或者让代码在提供内容时生成内容,您通常就可以自己实现这些内容。

    The idea is pretty simple: When you generate a page, you give the browser a little extra information about exactly what was on the page you sent. When the browser asks for the same page again, it gives you this information back. If it matches what you were going to send, you know that the browser already has a copy and send a much smaller 304 (Not Modified) reply instead of the contents of the page again. And if you are clever about what information you include in an ETag, you can usually skip the most expensive database queries that would've gone into generating the page.

    这个想法很简单:当你生成一个页面时,你给浏览器一些额外的信息,告诉你发送的页面上到底有什么。当浏览器再次请求同一页面时,它会返回此信息。如果它与您要发送的内容匹配,您就知道浏览器已经有副本,并再次发送更小的 304(未修改)回复而不是页面内容。如果你对 ETag 中包含的信息很聪明,你通常可以跳过生成页面时最昂贵的数据库查询。

  • Minimize HTTP request size. Often cookies are set domain-wide, which means they are also unnecessarily sent by the browser with every image request from within that domain. What might've been a 400 byte request for an image could easily turn into 1000 bytes or more once you add the cookie headers. If you have a lot of uncached or uncacheable objects per page and big, domain-wide cookies, consider using a separate domain to host static content, and be sure to never set any cookies in it.

    最小化 HTTP 请求大小。通常,Cookie 是在整个域范围内设置的,这意味着浏览器也会不必要地随域内的每个图像请求一起发送它们。添加 cookie 标头后,对图像的 400 字节请求很容易变成 1000 字节或更多。如果每个页面都有很多未缓存或不可缓存的对象,并且有大型的域范围 Cookie,请考虑使用单独的域来托管静态内容,并确保永远不要在其中设置任何 Cookie。

    Minimize HTTP response size by enabling gzip compression for HTML and XML for browsers that support it. For example, the 17k document you are reading takes 90ms of the full downstream bandwidth of a user on 1.5Mbit DSL. Or it will take 37ms when compressed to 6.8k. That's 53ms off of the full page load time for a simple change. If your HTML is bigger and more redundant, you'll see an even greater improvement.

    通过为支持 HTTP 的浏览器启用 HTML 和 XML 的 gzip 压缩,将 HTTP 响应大小降至最低。例如,您正在阅读的 17k 文档占用了 1.5Mbit DSL 上用户的完整下行带宽的 90ms。或者压缩到 37k 时需要 6.8ms。对于简单的更改,这比整个页面加载时间少了 53 毫秒。如果你的 HTML 更大、更冗余,你会看到更大的改进。

    If you are brave, you could also try to figure out which set of browsers will handle compressed Javascript properly. (Hint: IE4 through IE6 asks for its javascript compressed, then breaks badly if you send it that way.) Or look into Javascript obfuscators that strip out whitespace, comments, etc and usually get it down to 1/3 to 1/2 its original size.

    如果你勇敢的话,你也可以试着弄清楚哪一组浏览器可以正确处理压缩的Javascript。(提示:IE4 到 IE6 要求压缩其 javascript,如果您以这种方式发送,则会严重中断。或者查看 Javascript 混淆器,它们会去除空格、注释等,通常将其缩小到原始大小的 1/3 到 1/2。

  • Consider locating your small objects (or a mirror or cache of them) closer to your users in terms of network latency. For larger sites with a global reach, either use a commercial Content Delivery Network, or add a colo within 50ms of 80% of your users and use one of the many available methods for routing user requests to your colo nearest them.

    就网络延迟而言,请考虑将小对象(或它们的镜像或缓存)放置在离用户更近的位置。对于具有全球影响力的大型网站,请使用商业内容分发网络,或者在 80% 的用户的 50 毫秒内添加一个 colo,并使用众多可用方法之一将用户请求路由到离他们最近的 colo。

  • Regularly use your site from a realistic net connection. Convincing the web developers on my project to use a "slow proxy" that simulates bad DSL in New Zealand (768Kbit down, 128Kbit up, 250ms RTT, 1% packet loss) rather than the gig ethernet a few milliseconds from the servers in the U.S. was a huge win. We found and fixed a number of usability and functional problems very quickly.

    定期从现实的网络连接使用您的网站。说服我项目中的 Web 开发人员使用"慢速代理"来模拟新西兰的不良 DSL(768Kbit down、128Kbit up、250ms RTT、1% 数据包丢失)而不是距离美国服务器几毫秒的千兆以太网,这是一个巨大的胜利。我们很快发现并修复了许多可用性和功能问题。

    To implement the slow proxy, I used the netem and HTB kernel modules available in the Linux 2.6 kernel, both of which are set up with the tc command line tool. These offer the most accurate simulation I could find, but are definitely not for the faint of heart. I've not used them, but supposedly Tamper Data for Firefox, Fiddler for Windows, and Charles for OSX can all rate-limit and are probably easier to set up, but they may not simulate latency properly.

    为了实现慢速代理,我使用了 Linux 2.6 内核中提供的 netem 和 HTB 内核模块,这两个模块都是使用 tc 命令行工具设置的。这些提供了我能找到的最准确的模拟,但绝对不适合胆小的人。我没有使用过它们,但据说 Firefox 的 Tamper Data、Windows 的 Fiddler 和 OSX 的 Charles 都可以进行速率限制,并且可能更容易设置,但它们可能无法正确模拟延迟。

  • Use Firebug for Firefox from a realistic net connection to see a graphical timeline of what it is doing during a page load. This shows where Firefox has to wait for one HTTP request to complete before starting the next one and how page load time increases with each object loaded. YSlow extends Firebug to offer tips on how to improve your site's performance.

    从真实的网络连接中使用 Firebug for Firefox,查看它在页面加载期间所做操作的图形时间线。这显示了 Firefox 在启动下一个 HTTP 请求之前必须等待一个 HTTP 请求完成的位置,以及页面加载时间如何随着每个对象的加载而增加。YSlow 扩展了 Firebug,以提供有关如何提高网站性能的提示。

    The Safari team offers a tip on a hidden feature in their browser that offers some timing data too.

    Safari 团队提供了有关浏览器中隐藏功能的提示,该功能也提供了一些计时数据。

    Or if you are familiar with the HTTP protocol and TCP/IP at the packet level, you can watch what is going on using tcpdump, ngrep, or ethereal. These tools are indispensable for all sorts of network debugging.

    或者,如果您熟悉数据包级别的 HTTP 协议和 TCP/IP,则可以使用 tcpdump、ngrep 或 ethereal 来观察正在发生的事情。这些工具对于各种网络调试都是必不可少的。

  • Try benchmarking common pages on your site from a local network with ab, which comes with the Apache webserver. If your server is taking longer than 5 or 10 milliseconds to generate a page, you should make sure you have a good understanding of where it is spending its time.

    尝试使用 Apache Web 服务器附带的 ab 从本地网络对站点上的常见页面进行基准测试。如果您的服务器生成页面的时间超过 5 或 10 毫秒,您应该确保对它花费的时间有很好的了解。

    If your latencies are high and your webserver process (or CGI if you are using that) is eating a lot of CPU during this test, it is often a result of using a scripting language that needs to recompile your scripts with every request. Software like eAccelerator for PHP, mod_perl for perl, mod_python for python, etc can cache your scripts in a compiled state, dramatically speeding up your site. Beyond that, look at finding a profiler for your language that can tell you where you are spending your CPU. If you improve that, your pages will load faster and you'll be able to handle more traffic with fewer machines.

    如果你的延迟很高,并且你的 Web 服务器进程(或者 CGI,如果你正在使用它)在此测试期间消耗了大量的 CPU,这通常是使用脚本语言的结果,该语言需要在每次请求时重新编译你的脚本。eAccelerator for PHP、mod_perl for perl、mod_python for python 等软件可以在编译状态下缓存您的脚本,从而大大加快您的网站速度。除此之外,还可以考虑为您的语言找到一个分析器,它可以告诉您在哪里花费了 CPU。如果你改进了这一点,你的页面加载速度会更快,你将能够用更少的机器处理更多的流量。

    If your site relies on doing a lot of database work or some other time-consuming task to generate the page, consider adding server-side caching of the slow operation. Most people start with writing a cache to local memory or local disk, but that starts to fall down if you expand to more than a few web server machines. Look into using memcached, which essentially creates an extremely fast shared cache that's the combined size of the spare RAM you give it off of all of your machines. It has clients available in most common languages.

    如果您的网站依赖于执行大量数据库工作或其他一些耗时的任务来生成页面,请考虑添加慢速操作的服务器端缓存。大多数人从将缓存写入本地内存或本地磁盘开始,但是如果扩展到多个 Web 服务器计算机,则这种情况会开始下降。考虑使用 memcached,它本质上会创建一个非常快速的共享缓存,该缓存是您从所有机器中提供的备用 RAM 的总大小。它有大多数常用语言的客户端。

  • (Optional) Petition browser vendors to turn on HTTP pipelining by default on new browsers. Doing so will remove some of the need for these tricks and make much of the web feel much faster for the average user. (Firefox has this disabled supposedly because some proxies, some load balancers, and some versions of IIS choke on pipelined requests. But Opera has found sufficient workarounds to enable pipelining by default. Why can't other browsers do similarly?)

    (可选)请求浏览器供应商在新浏览器上默认启用 HTTP 流水线。这样做将消除对这些技巧的一些需求,并使普通用户感觉大部分网络更快。(Firefox禁用此功能可能是因为某些代理,某些负载均衡器和某些版本的IIS会阻塞流水线请求。但 Opera 已经找到了足够的解决方法来默认启用流水线。为什么其他浏览器不能做类似的操作?

The above list covers improving the speed of communication between browser and server and can be applied generally to many sites, regardless of what web server software they use or what language the code behind your site is written in. There is, unfortunately, a lot that isn't covered.

上面的列表涵盖了提高浏览器和服务器之间的通信速度,并且通常可以应用于许多站点,无论它们使用什么 Web 服务器软件或站点背后的代码是用什么语言编写的。不幸的是,有很多内容没有被涵盖。

While the tips above are intended to improve your page load times, a side benefit of many of them is a reduction in server bandwidth and CPU needed for the average page view. Reducing your costs while improving your user experience seems it should be worth spending some time on.

虽然上述提示旨在缩短页面加载时间,但其中许多提示的附带好处是减少了平均页面浏览所需的服务器带宽和 CPU。在改善用户体验的同时降低成本似乎值得花一些时间。

-- Aaron Hopkins ------亚伦·霍普金斯


via: Optimizing Page Load Time -- Aaron Hopkins


另一篇相关方法比较

提高页面加载速度的 9 种快速方法

When it comes to your site's performance, page speed is of the utmost importance.

当涉及到您网站的性能时,页面速度至关重要。

However, unless you understand how this metric works --- and, more specifically, the factors that influence it --- you may find it difficult to improve.

但是,除非您了解此指标的工作原理,以及更具体地说,影响它的因素,否则您可能会发现很难改进。

To reduce your [bounce rate](https://blog.hubspot.com/marketing/what-is-bounce-rate-fix?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=bounce rate) and increase visitor engagement, it's essential that your web pages load quickly and seamlessly.

为了降低跳出率并提高访问者的参与度,您的网页必须快速无缝地加载。

A site that is optimized for speed not only enhances the user experience (UX) but can also help to boost your search engine rankings.

针对速度进行优化的网站不仅可以增强用户体验 (UX),还可以帮助提高您的搜索引擎排名。

In this article, we'll explain what page speed is, why it's important, and how to measure it. Then we'll provide you with nine quick solutions you can use to improve page loading speed.

在本文中,我们将解释什么是页面速度,为什么它很重要,以及如何衡量它。然后,我们将为您提供九种快速解决方案,您可以使用它们来提高页面加载速度。

Let's get started! 让我们开始吧!

What is page speed? 什么是页面速度?

In a nutshell, page speed refers to how quickly your content loads when someone visits a page on your site. Not to be confused with website speed, page speed represents the loading time of a specific page.

简而言之,页面速度是指当有人访问您网站上的页面时,您的内容加载速度。不要与网站速度混淆,页面速度代表特定页面的加载时间。

There are a variety of factors that can influence page speed. Some of the most important include:

有多种因素会影响页面速度。其中一些最重要的包括:

  • How many images, videos, and other media files are contained on the page
    页面上包含多少个图像、视频和其他媒体文件
  • What themes and plugins are installed on your site
    您的网站上安装了哪些主题和插件
  • Your site's (and the specific page's) coding and server-side scripts
    您网站(以及特定页面)的编码和服务器端脚本

All of these elements affect your page loading speed and in turn your website's UX. After all, visitors dislike slow-loading pages and are more likely to click away from them.

所有这些元素都会影响您的页面加载速度,进而影响您网站的用户体验。毕竟,访问者不喜欢加载缓慢的页面,并且更有可能点击离开它们。

Why is page speed important? 为什么页面速度很重要?

When it comes to page loading speed, every second counts. In fact, Google research shows that when loading times increase from one to three seconds, the probability of a bounce (the visitor leaving right away) increases by 32 percent.

在页面加载速度方面,每一秒都很重要。事实上,谷歌研究表明,当加载时间从一秒增加到三秒时,反弹(访问者立即离开)的概率增加了 32%。

If the page takes five seconds to load, the probability of a bounce rises by 90 percent

如果页面加载需要 5 秒钟,则退回的概率会增加 90%

In other words, if your pages don't load within a few seconds, it significantly increases the chance that visitors will leave your site. Additionally, if your web pages are sluggish, that can hurt your ability to drive engagement and conversions.

换句话说,如果您的页面在几秒钟内没有加载,则会显着增加访问者离开您网站的机会。此外,如果您的网页运行缓慢,这可能会损害您推动参与度和转化的能力。

Page speed also plays a pivotal role in [Search Engine Optimization (SEO)](https://blog.hubspot.com/marketing/what-is-seo?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=Search Engine Optimization (SEO)). Google takes a wide variety of factors into consideration when deciding how to rank web pages.

页面速度在搜索引擎优化 (SEO) 中也起着举足轻重的作用。谷歌在决定如何对网页进行排名时会考虑多种因素。

However, speed is an important ranking signal for both desktop and mobile searches.

然而,速度是桌面和移动搜索的重要排名信号。

Another reason page speed matters is because it can influence consumers' perception of your brand. If your web pages take too long to load or anything goes wrong during the process, it can make you look unprofessional, and your website unreliable.

页面速度很重要的另一个原因是因为它会影响消费者对您的品牌的看法。如果您的网页加载时间过长或在此过程中出现任何问题,可能会使您看起来不专业,并且您的网站不可靠。

If you want to run a highly-effective website, therefore, it's necessary to focus on optimizing page speed. The first step in doing that is figuring out how your pages are currently performing.

因此,如果您想运行一个高效的网站,则必须专注于优化页面速度。这样做的第一步是弄清楚您的页面当前的表现如何。

How to Measure Page Speed 如何测量页面速度

Before making any changes to your site, you'll need to gauge your web pages' performance. There are various tools you can use to test and measure page speed. Two popular solutions are Pingdom Website Speed Test and GTmetrix, which are both beginner-friendly options.

在对您的网站进行任何更改之前,您需要评估网页的性能。您可以使用各种工具来测试和测量页面速度。两种流行的解决方案是 Pingdom 网站速度测试和 GTmetrix,它们都是适合初学者的选择。

However, we recommend starting with Google PageSpeed Insights. This is an easy-to-use tool that enables you to measure and test the speed of your web pages on both desktop and mobile devices.

但是,我们建议您从 Google PageSpeed Insights 开始。这是一个易于使用的工具,可让您在桌面和移动设备上测量和测试网页的速度。

Plus, as a Google-supported tool, it can help you make sure you're hitting the performance benchmarks required for high search result placements.

此外,作为 Google 支持的工具,它可以帮助您确保达到高搜索结果展示位置所需的性能基准。

To use PageSpeed Insights, simply enter the URL of the web page you want to test into the text field, and select the Analyze button

要使用 PageSpeed Insights,只需在文本字段中输入要测试的网页的 URL,然后选择"分析"按钮

PageSpeed Insights will then analyze the content on your page, and score it on a scale of 0 to 100. Below your score, you'll find a list of suggestions on ways you can improve page loading speed

然后,PageSpeed Insights 将分析您页面上的内容,并以 0 到 100 的等级对其进行评分。在您的分数下方,您会找到有关提高页面加载速度的方法的建议列表

It's worth noting that you'll get a separate score and list of suggestions for both the desktop and mobile versions of your site.

值得注意的是,您将获得针对您网站的桌面版和移动版的单独分数和建议列表。

This information gives you a solid starting point for gauging how fast your web pages are, and offers tangible actions you can take to improve page loading speeds.

这些信息为您提供了一个坚实的起点来衡量您的网页的速度,并提供了您可以采取的切实行动来提高页面加载速度。

9 种快速方法

Now that you understand the importance of page speed and how to test your site's performance, it's time to work on improving this key metric.

现在您已经了解了页面速度的重要性以及如何测试网站的性能,是时候努力改进这一关键指标了。

With that in mind, let's take a look at nine easy ways to make your pages load faster.

考虑到这一点,让我们来看看九种简单的方法可以让你的页面加载速度更快。

1. Choose a performance-optimized hosting solution. 1. 选择性能优化的托管解决方案。

The hosting provider you use plays a major role in your website's management and performance. That includes its page speeds.

您使用的托管服务提供商在您网站的管理和性能中起着重要作用。这包括它的页面速度。

One of the worst mistakes you can make is settling for mediocre hosting in order to get a lower monthly rate.

您可能犯的最严重的错误之一是满足于平庸的托管以获得较低的月费率。

Cheap hosting often translates to poor performance. It can mean sharing resources between multiple websites on an overloaded server, which can end up straining your page loading times.

廉价的托管通常意味着性能不佳。这可能意味着在过载的服务器上的多个网站之间共享资源,这最终可能会使您的页面加载时间紧张。

On the other hand, there are a handful of performance-focused hosting solutions you can use such as SiteGround and Kinsta that provide a powerful platform designed for speed. Usually, these providers don't offer shared hosting, which means you'll never have to worry about other websites draining your pool of potential resources.

另一方面,您可以使用一些以性能为中心的托管解决方案,例如 SiteGround 和 Kinsta,它们提供了一个专为速度而设计的强大平台。通常,这些提供商不提供共享主机,这意味着您永远不必担心其他网站会耗尽您的潜在资源池。

2. Compress and optimize your images. 2. 压缩和优化您的图像。

Images help enhance the appearance of your web pages and increase the quality of your content. However, large images can also delay loading times.

图像有助于增强网页的外观并提高内容的质量。但是,大图像也会延迟加载时间。

Therefore, one of the easiest ways to increase page loading speeds is to compress and optimize your images. This can include changing their file formats, enabling lazy loading, and compressing images through lossy or lossless compression.

因此,提高页面加载速度的最简单方法之一是压缩和优化图像。这可能包括更改其文件格式、启用延迟加载以及通过有损或无损压缩压缩图像。

By reducing your images' file sizes, you can reduce their 'weight', ultimately helping your pages load more quickly. There are a variety of image optimization plugins you can use for this purpose, such as WP Smush.

通过减小图像的文件大小,您可以减轻它们的"重量",最终帮助您的页面更快地加载。您可以使用多种图像优化插件来实现此目的,例如 WP Smush。

After you install and activate this plugin, it will automatically resize and compress your images without affecting their quality. It includes features for lossless compression, lazy loading, and even optimizing images in bulk.

安装并激活此插件后,它将自动调整图像大小和压缩图像,而不会影响其质量。它包括无损压缩、延迟加载甚至批量优化图像的功能。

Another very effective plugin for WordPress websites is the SiteGround Optimizer plugin. It offers powerful image compression options that can reduce your image size by up to 85% without compromising image quality. Additionally, the plugin provides an option for using the WebP image format, lazy loading, and other image optimization features that can significantly decrease your media size and improve your loading speed. The plugin is completely free and easy to use.

另一个非常有效的 WordPress 网站插件是 SiteGround Optimizer 插件。它提供了强大的图像压缩选项,可以在不影响图像质量的情况下将图像大小减少多达 85%。此外,该插件还提供了一个使用 WebP 图像格式、延迟加载和其他图像优化功能的选项,这些功能可以显着减小您的媒体大小并提高您的加载速度。该插件是完全免费且易于使用的。

If you're not using WordPress as your CMS, you might want to try with tinypng.com or Attrock, which can reduce your image sizes anywhere from 25% to 80%, and a free website app called Squoosh.

如果您不使用 WordPress 作为您的 CMS,您可能需要尝试使用 tinypng.com 或 Attrock,它们可以将您的图像大小从 25% 减少到 80%,以及一个名为 Squoosh 的免费网站应用程序。

3. Reduce your redirects. 3. 减少重定向。

Too many redirects on your website can really hurt loading times. [Every time a page redirects somewhere else](https://blog.hubspot.com/blog/tabid/6307/bid/7430/what-is-a-301-redirect-and-why-should-you-care.aspx?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=Every time a page redirects somewhere else), it prolongs the HTTP request and response process.

您网站上的重定向过多确实会损害加载时间。每当页面重定向到其他地方时,它都会延长 HTTP 请求和响应过程。

Of course, in some cases redirects may be necessary, such as when you're moving to a new domain. However, eliminating unnecessary redirects on your site can result in significantly lower page loading times.

当然,在某些情况下,重定向可能是必要的,例如当您移动到新域时。但是,消除网站上不必要的重定向可以显着缩短页面加载时间。

There are a few different ways to reduce redirects in WordPress. One is to avoid creating unnecessary ones when building internal links and menus. Another is making sure your [Top-Level Domain (TLD)](https://blog.hubspot.com/website/what-is-a-domain?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=Top-Level Domain (TLD)) resolves with a maximum of one redirection.

有几种不同的方法可以减少 WordPress 中的重定向。一是在构建内部链接和菜单时避免创建不必要的链接和菜单。另一个是确保您的顶级域 (TLD) 最多只能进行一次重定向。

If you need help identifying redirects that are incorrectly set up on your site, you can use the Patrick Sexton Redirect mapper tool

如果您需要帮助来识别网站上设置不正确的重定向,可以使用 Patrick Sexton 重定向映射器工具

This will uncover any duplicate redirects. You can also use a tool such as Screaming Frog to identify all the redirects on your site and where they lead to. This should make it easier to identify redirects that aren't serving a purpose. Then you can delete the ones you don't need via your site's .htaccess file.

这将发现任何重复的重定向。您还可以使用诸如 Screaming Frog 之类的工具来识别您网站上的所有重定向以及它们指向的位置。这应该可以更容易地识别没有目的的重定向。然后,您可以通过网站的 .htaccess 文件删除不需要的内容。

4. Cache your web pages. 4. 缓存您的网页。

Caching is one of the most effective ways to speed up your web pages. Caching stores copies of your site's files, minimizing the work needed for the server to generate and serve a web page to a visitor's browser.

缓存是加快网页速度的最有效方法之一。缓存存储站点文件的副本,从而最大限度地减少服务器生成网页并将其提供给访问者浏览器所需的工作。

Caching your web pages can help with lowering Time to First Byte (TTFB), by requiring the server to use fewer resources to load a page.

缓存网页可以帮助降低到第一个字节的时间 (TTFB),因为它要求服务器使用更少的资源来加载页面。

There are various ways to cache your web pages. You can do this at the server level, meaning that your host handles it for you.

有多种方法可以缓存您的网页。您可以在服务器级别执行此操作,这意味着您的主机会为您处理它。

Another option is to use a [caching plugin](https://blog.hubspot.com/website/best-wordpress-cache-plugins-to-speed-up-a-site?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=caching plugin) such as W3 Total Cache, which is a free WordPress plugin that makes caching your web pages quick and easy. After you install and activate it, simply navigate to General Settings > Page Cache and select the Enable option.

另一种选择是使用缓存插件,例如 W3 Total Cache,这是一个免费的 WordPress 插件,可以快速轻松地缓存您的网页。安装并激活它后,只需导航到"常规设置">"页面缓存",然后选择"启用"选项。

You can also take advantage of WP Rocket, a powerful caching plugin that will boost your loading time and optimize your PageSpeed Insights score and Core Web Vitals in just a few clicks. Plus, the plugin applies 80% of web performance best practices upon activation -- the perfect tool to save time and make your site faster.

您还可以利用 WP Rocket,这是一个功能强大的缓存插件,只需单击几下即可延长您的加载时间并优化您的 PageSpeed Insights 分数和 Core Web Vitals。此外,该插件在激活时应用了 80% 的 Web 性能最佳实践------这是节省时间并使您的网站更快的完美工具。

Another useful solution for your WordPress website is the free SiteGround Optimizer plugin that offers powerful caching technologies, such as dynamic caching, object caching, file-based caching, and other caching settings. All of these can make your site load up to 20% faster than comparable plugins.

WordPress网站的另一个有用的解决方案是免费的SiteGround Optimizer插件,它提供了强大的缓存技术,例如动态缓存,对象缓存,基于文件的缓存和其他缓存设置。所有这些都可以使您的网站加载速度比同类插件快 20%。

5. Enable browser caching. 5. 启用浏览器缓存。

[Browser caching](https://blog.hubspot.com/marketing/what-is-browser-cache-faqs?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=Browser caching) is another form of caching you can leverage to improve page loading speeds. This technique enables the browser to store a variety of information, including stylesheets, images, and JavaScript files, so it doesn't have to reload the entire page every time a user visits it.

浏览器缓存是另一种缓存形式,您可以利用它来提高页面加载速度。这种技术使浏览器能够存储各种信息,包括样式表、图像和 JavaScript 文件,因此不必在每次用户访问时都重新加载整个页面。

Similar to W3 Total Cache, WP Rocket is a powerful caching plugin you can use on your WordPress site. It employs page caching and cache pre-loading to optimize the speed of your pages, and create lightning-fast loading times. WP Rocket is a premium plugin, with a variety of pricing plans to choose from.

与 W3 Total Cache 类似,WP Rocket 是一个功能强大的缓存插件,您可以在 WordPress 网站上使用。它采用页面缓存和缓存预加载来优化页面的速度,并创建闪电般的加载时间。WP Rocket 是一个高级插件,有多种定价计划可供选择。

Browser caching is also offered by the free SiteGround Optimizer plugin and it's easy to use for both non-technical and experienced site owners alike.

免费的SiteGround Optimizer插件也提供浏览器缓存,对于非技术人员和有经验的网站所有者来说,它都易于使用。

6. Use asynchronous and defer loading for your CSS and JavaScript files. 6. 对 CSS 和 JavaScript 文件使用异步和延迟加载。

Your site is made up of CSS and JavaScript files. These scripts can load either synchronously or asynchronously.

您的网站由 CSS 和 JavaScript 文件组成。这些脚本可以同步或异步加载。

Synchronously means that the files load one at a time, in the order in which they appear on your web page.

同步意味着文件按照它们在网页上的显示顺序一次加载一个文件。

With this method, when the browser encounters a script, it will stop loading other elements on the page until that file has been fully loaded first.

使用此方法,当浏览器遇到脚本时,它将停止加载页面上的其他元素,直到该文件首先被完全加载。

Conversely, [asynchronous loading](https://blog.hubspot.com/marketing/reduce-http-requests?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=asynchronous loading) enables multiple files to load at the same time, which can speed up the page's performance. Setting this up involves eliminating render-blocking resources.

相反,异步加载允许同时加载多个文件,这可以加快页面的性能。设置此项涉及消除渲染阻塞资源。

If you're using WordPress, you could either use a combination of the Autoptimize and Async JavaScript plugins to take care of this task easily.

如果您使用的是 WordPress,则可以使用 Autoptimize 和 Async JavaScript 插件的组合来轻松完成此任务。

You could also go for the most straightforward option and use WP Rocket. The plugin includes three effective features to optimize CSS and Javascript files: Remove unused CSS, Load JavaScript deferred, and Delay JavaScript execution. You only need to enable the options, and the plugin will take care of the file optimization.

您也可以选择最直接的选项并使用 WP Rocket。该插件包括三个优化 CSS 和 Javascript 文件的有效功能:删除未使用的 CSS、延迟加载 JavaScript 和延迟 JavaScript 执行。您只需要启用选项,插件就会负责文件优化。

Another option is the free SiteGround Optimizer plugin. It includes many features for optimizing CSS and JavaScript files - CSS and JavaScript combination, deferring the loading of render-blocking JavaScript, and many others.

另一种选择是免费的 SiteGround Optimizer 插件。它包括许多用于优化 CSS 和 JavaScript 文件的功能 - CSS 和 JavaScript 组合、延迟渲染阻塞 JavaScript 的加载等等。

7. Minify CSS, JavaScript, and HTML. 7. 缩小 CSS、JavaScript 和 HTML。

Optimizing the way your files load can help improve page loading speed. Similarly, so can [minifying your CSS, JavaScript, and HTML code](https://blog.hubspot.com/marketing/reducing-page-size?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=minifying your CSS%2C JavaScript%2C and HTML code). This means removing unnecessary spaces, characters, comments, and other unneeded elements to reduce the size of the files.

优化文件加载方式有助于提高页面加载速度。同样,缩小 CSS、JavaScript 和 HTML 代码也是如此。这意味着删除不必要的空格、字符、注释和其他不需要的元素以减小文件的大小。

Decreasing your files' sizes also makes it easier to combine them. The result is cleaner code, and leaner web pages that load faster.

减小文件的大小还可以更轻松地组合它们。结果是更简洁的代码和更精简的网页,加载速度更快。

Of course, combing through every line of code for each of your site's files isn't exactly efficient.

当然,梳理每个网站文件的每一行代码并不完全有效。

Instead, you can minify your CSS, JavaScript, and HTML with a free plugin: Autoptimize instead. This popular plugin makes it easy to aggregate and minify your scripts and styles automatically:

相反,您可以使用免费插件缩小 CSS、JavaScript 和 HTML:Autoptimize。这个流行的插件可以很容易地自动聚合和缩小你的脚本和样式

Considering the wide variety of features and settings it offers, configuring this plugin can be a bit overwhelming at first. To make your job easier, feel free to check out this guide on how to set up Autoptimize on your website.

考虑到它提供的各种功能和设置,配置此插件一开始可能会有点不知所措。为了让您的工作更轻松,请随时查看本指南,了解如何在您的网站上设置 Autoptimize。

To save yourself some time and effort, you can try the SiteGround Optimizer plugin which offers effective minification feaetures (among other things). You can enable HTTML, CSS, and JavaScript minification in one click to make your files more lightweight.

为了节省一些时间和精力,您可以尝试 SiteGround Optimizer 插件,它提供有效的缩小功能(除其他外)。您可以一键启用 HTTML、CSS 和 JavaScript 缩小,使您的文件更轻量级。

8. Leverage a content delivery network (CDN). 8. 利用内容分发网络 (CDN)。

A [Content Delivery Network (CDN)](https://blog.hubspot.com/marketing/what-is-a-cdn-definition?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=Content Delivery Network (CDN)), also referred to as a 'content distribution network', is a network of servers that can help improve page loading speed. It does this by hosting and delivering copies of your site's static content from servers located across the globe.

内容分发网络 (CDN),也称为"内容分发网络",是一种可以帮助提高页面加载速度的服务器网络。它通过托管和交付来自全球服务器的站点静态内容的副本来实现这一点。

A CDN works with, rather than in place of, your host. In addition to the server that hosts your primary website, you can leverage a CDN to distribute copies of your site's files among strategically-chosen data centers.

CDN 与主机一起工作,而不是代替主机。除了托管主网站的服务器外,您还可以利用 CDN 在战略选择的数据中心之间分发站点文件的副本。

[This can maximize performance](https://blog.hubspot.com/customers/3-ways-hubspot-keeps-your-website-fast?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=This can maximize performance), by reducing the distance data requests have to travel between browsers and your host's servers. By loading the content for a web page from a server close to each visitor, a CDN helps reduce network latency and produce lower TTFBs.

这可以通过减少数据请求在浏览器和主机服务器之间传输的距离来最大限度地提高性能。通过从靠近每个访问者的服务器加载网页内容,CDN 有助于减少网络延迟并产生更低的 TTFB。

You have a [variety of CDN options to choose from](https://blog.hubspot.com/website/best-free-cdn-services-to-speed-up-wordpress?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=variety of CDN options to choose from), one of which is opting for a host that provides a CDN you can enable it directly from your own dashboard.

您有多种 CDN 选项可供选择,其中之一是选择提供 CDN 的主机,您可以直接从自己的仪表板启用它。

9. Eliminate unnecessary plugins. 9.消除不必要的插件。

Not all plugins are created equal. Having too many plugins on your site can cause unnecessary bloat that slows it down.

并非所有插件都是平等的。您的网站上有太多插件可能会导致不必要的膨胀,从而减慢速度。

Additionally, plugins that are outdated or aren't well maintained can pose a [security threat](https://blog.hubspot.com/website/wordpress-security-issues?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=security threat), and even introduce compatibility issues that hamper performance.

此外,过时或维护不善的插件可能会构成安全威胁,甚至会引入阻碍性能的兼容性问题。

Therefore, it's a smart idea to minimize the number of plugins you use on your WordPress site. Of course, one of the easiest ways to do this is by disabling and deleting any plugins you don't currently use.

因此,尽量减少您在 WordPress 网站上使用的插件数量是一个明智的主意。当然,最简单的方法之一是禁用和删除您当前不使用的任何插件。

We also recommend reviewing the plugins you have installed, to evaluate whether they're actually necessary. There might be some tools that have overlapping functionalities and features, and others that are simply no longer relevant to your needs.

我们还建议您查看已安装的插件,以评估它们是否真的有必要。可能有些工具具有重叠的功能和特性,而另一些工具则不再与您的需求相关。

Finally, certain plugins may slow your site down more than others. To identify any plugins that are reducing your page speeds, you can try testing them individually.

最后,某些插件可能会比其他插件更慢您的网站。要识别任何降低页面速度的插件,您可以尝试单独测试它们。

First, deactivate all of your plugins (it's safest to do this on a staging site)

首先,停用所有插件(在暂存站点上执行此操作是最安全的)

Then turn them back on one by one. Each time you activate a plugin, use a speed testing tool such as PageSpeed Insights to see if your score and timings have been affected.

然后一个接一个地重新打开它们。每次激活插件时,请使用速度测试工具(例如 PageSpeed Insights)查看您的分数和时间是否受到影响。

Many plugins might increase your page speeds by a small margin. However, if you see a sudden large increase, it may be time to find an alternative tool that serves the same purpose (but is better optimized).

许多插件可能会将您的页面速度提高一小部分。但是,如果您看到突然大幅增加,可能是时候找到一种具有相同目的(但优化得更好)的替代工具了。

Ultimately, reducing page loading speed improves not only the overall performance and UX of your website but its [SEO as well](https://blog.hubspot.com/marketing/seo?hubs_content=blog.hubspot.com/marketing/how-to-reduce-your-websites-page-speed\&hubs_content-cta=SEO as well). Luckily for you, there are a variety of methods you can use to decrease your loading times.

最终,降低页面加载速度不仅可以提高网站的整体性能和用户体验,还可以提高其搜索引擎优化。幸运的是,您可以使用多种方法来减少加载时间。

In addition to leveraging a CDN and caching your pages, you can use plugins to optimize your images, defer loading scripts, and minify your site's files.

除了利用 CDN 和缓存页面外,您还可以使用插件来优化图像、延迟加载脚本和缩小网站文件。

Using a hosting solution optimized for performance can also have a major influence on your site's speed.

使用针对性能优化的托管解决方案也会对您网站的速度产生重大影响。

Remember, though --- every second your web pages take to load drastically increases the chance your visitors will leave. How long will you able to run your business while losing leads?

但请记住,您的网页加载每一秒钟都会大大增加访问者离开的机会。在失去潜在客户的同时,您将能够经营业务多长时间?


via: 9 Quick Ways to Improve Page Loading Speed

Matteo Duò

Published: October 15, 2020

Updated: May 12, 2023

相关推荐
Diamond技术流10 天前
从0开始学习Linux——文件管理
linux·运维·学习·安全·文件·权限·极限编程
Oo_Amy_oO15 天前
【极限编程(XP)】
低代码·极限编程
帅次25 天前
基于边缘计算的智能门禁系统架构设计分析
软件工程·团队开发·软件构建·需求分析·规格说明书·代码复审·极限编程
冰暮流星2 个月前
极限编程XP例题
笔记·极限编程
码力码力我爱你3 个月前
C++现代教程四
开发语言·c++·算法·极限编程
斐夷所非4 个月前
挑战英伟达的护城河 —— SCALE 源码直译让 CUDA 程序跑上 AMD
极限编程
斐夷所非4 个月前
I18N/L10N 历史 / I18N 指南 / libi18n 模块说明
极限编程
斐夷所非5 个月前
“Hello, World!“ 历史由来
极限编程
斐夷所非5 个月前
Code Page 历史
极限编程