创作快速加载 HTML 页面的技巧

这些技巧基于常识和实验。

¥These tips are based on common knowledge and experimentation.

优化的网页不仅可以为访问者提供响应更快的网站,还可以减少网络服务器和互联网连接的负载。这对于大流量网站或由于突发新闻等异常情况而导致流量激增的网站至关重要。

¥An optimized web page not only provides for a more responsive site for your visitors but also reduces the load on your web servers and internet connection. This can be crucial for high volume sites or sites which have a spike in traffic due to unusual circumstances such as breaking news stories.

优化页面加载性能不仅仅针对窄带拨号或移动设备访问者将查看的内容。它对于宽带内容同样重要,甚至对于拥有最快连接的访问者来说也可以带来显着的改进。

¥Optimizing page load performance is not just for content which will be viewed by narrowband dial-up or mobile device visitors. It is just as important for broadband content and can lead to dramatic improvements even for your visitors with the fastest connections.

提示

¥Tips

减少页面重量

¥Reduce page weight

页面权重是迄今为止页面加载性能中最重要的因素。

¥Page weight is by far the most important factor in page-load performance.

通过消除不必要的空白和注释(通常称为最小化)以及通过将内联脚本和 CSS 移至外部文件来减少页面重量,可以提高下载性能,并且无需对页面结构进行其他更改。

¥Reducing page weight through the elimination of unnecessary whitespace and comments, commonly known as minimization, and by moving inline script and CSS into external files, can improve download performance with minimal need for other changes in the page structure.

诸如 HTML 整洁 之类的工具可以自动从有效的 HTML 源中去除前导空格和多余的空行。其他工具可以通过重新格式化源代码或混淆源代码并用较短版本替换长标识符来对 JavaScript 进行 "compress"。

¥Tools such as HTML Tidy can automatically strip leading whitespace and extra blank lines from valid HTML source. Other tools can "compress" JavaScript by reformatting the source or by obfuscating the source and replacing long identifiers with shorter versions.

尽量减少文件数量

¥Minimize the number of files

减少网页中引用的文件数量会减少下载页面所需的 HTTP 连接数量,从而减少发送这些请求以及接收其响应的时间。

¥Reducing the number of files referenced in a web page lowers the number of HTTP connections required to download a page, thereby reducing the time for these requests to be sent, and for their responses to be received.

根据浏览器的缓存设置,它可能会为每个引用的文件发送带有 If-Modified-Since 标头的请求,询问该文件自上次下载以来是否已被修改。花费太多时间查询引用文件的最后修改时间可能会延迟网页的初始显示,因为浏览器必须在呈现页面之前检查每个文件的修改时间。

¥Depending on a browser's cache settings, it may send a request with the If-Modified-Since header for each referenced file, asking whether the file has been modified since the last time it was downloaded. Too much time spent querying the last modified time of the referenced files can delay the initial display of the web page, since the browser must check the modification time for each of these files, before rendering the page.

如果你在 CSS 中大量使用背景图片,则可以通过将图片组合成一个图片(称为图片精灵)来减少所需的 HTTP 查找次数。然后,你只需在每次需要背景时应用相同的图片并适当调整 x/y 坐标即可。此技术最适合尺寸有限的元素,并且不适用于背景图片的每次使用。但是,较少的 HTTP 请求和单个图片缓存有助于减少页面加载时间。

¥If you use background images a lot in your CSS, you can reduce the number of HTTP lookups needed by combining the images into one, known as an image sprite. Then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately. This technique works best with elements that will have limited dimensions, and will not work for every use of a background image. However, the fewer HTTP requests and single image caching can help reduce page-load time.

使用内容分发网络 (CDN)

¥Use a Content Delivery Network (CDN)

就本文而言,CDN 是一种缩短服务器和访问者之间物理距离的方法。随着服务器源和访问者之间距离的增加,加载时间将会增加。假设你的网站服务器位于美国,并且有来自印度的访问者;与美国访问者相比,印度访问者的页面加载时间要长得多。

¥For the purposes of this article, a CDN is a means to reduce the physical distance between your server and your visitor. As the distance between your server origin and visitor increases, the load times will increase. Suppose your website server is located in the United States and it has a visitor from India; the page load time will be much higher for the Indian visitor compared to a visitor from the US.

CDN 是一个地理上分布的服务器网络,这些服务器协同工作以缩短用户和你的网站之间的距离。CDN 存储网站的缓存版本,并通过距离用户最近的网络节点将其提供给访问者,从而减少 latency

¥A CDN is a geographically distributed network of servers that work together to shorten the distance between the user and your website. CDNs store cached versions of your website and serve them to visitors via the network node closest to the user, thereby reducing latency.

进一步阅读:

¥Further reading:

减少域名查找

¥Reduce domain lookups

由于每个单独的域在 DNS 查找中都会花费时间,因此页面加载时间将随着 CSS 链接、JavaScript 和图片 src 中出现的单独域的数量而增长。

¥Since each separate domain costs time in a DNS lookup, the page load time will grow along with the number of separate domains appearing in CSS link(s) and JavaScript and image src(es).

这可能并不总是可行的;但是,你应该始终注意在页面中仅使用必要的最少数量的不同域。

¥This may not always be practical; however, you should always take care to use only the minimum necessary number of different domains in your pages.

缓存重用的内容

¥Cache reused content

确保所有可以缓存的内容都已缓存,并且具有适当的过期时间。

¥Make sure that any content that can be cached, is cached, and with appropriate expiration times.

特别要注意 Last-Modified 标头。它允许高效的页面缓存;通过此标头,将有关其要加载的文件的信息传送给用户代理,例如上次修改的时间。大多数 Web 服务器根据文件系统中存储的最后修改日期自动将 Last-Modified 标头附加到静态页面(例如 .html.css)。对于动态页面(例如 .php.aspx),这当然是无法完成的,并且不会发送标头。

¥In particular, pay attention to the Last-Modified header. It allows for efficient page caching; by means of this header, information is conveyed to the user agent about the file it wants to load, such as when it was last modified. Most web servers automatically append the Last-Modified header to static pages (e.g. .html, .css), based on the last-modified date stored in the file system. With dynamic pages (e.g. .php, .aspx), this, of course, can't be done, and the header is not sent.

因此,特别是对于动态生成的页面,对此主题进行一些研究是有益的。它可能会有所涉及,但它会在通常不可缓存的页面上节省大量页面请求。

¥So, in particular, for pages which are generated dynamically, a little research on this subject is beneficial. It can be somewhat involved, but it will save a lot in page requests on pages which would normally not be cacheable.

更多信息:

¥More information:

  1. 针对 RSS 黑客的 HTTP 条件获取
  2. HTTP 304:未修改
  3. 维基百科上的 HTTP ETag
  4. HTTP 中的缓存

优化页面组件的排序

¥Optimally order the components of the page

首先下载页面内容以及初始显示所需的任何 CSS 或 JavaScript,以便用户在页面加载期间获得最快的明显响应。该内容通常是文本,因此可以受益于传输中的文本压缩,从而为用户提供更快的响应。

¥Download page content first, along with any CSS or JavaScript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. This content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user.

任何需要页面在使用前完成加载的动态功能都应首先禁用,然后仅在页面加载后启用。这将导致 JavaScript 在页面内容之后加载,从而改善页面加载的整体外观。

¥Any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. This will cause the JavaScript to be loaded after the page contents, which will improve the overall appearance of the page load.

减少内联脚本的数量

¥Reduce the number of inline scripts

内联脚本对于页面加载来说可能会很昂贵,因为解析器必须假设内联脚本可以在解析过程中修改页面结构。一般来说,减少内联脚本的使用,特别是减少使用 document.write() 输出内容,可以改善整体页面加载。使用 用于操作页面内容的 DOM API,而不是 document.write()

¥Inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while parsing is in progress. Reducing the use of inline scripts in general, and reducing the use of document.write() to output content in particular, can improve overall page loading. Use DOM APIs to manipulate page content, rather than document.write().

使用现代 CSS 和有效的标记

¥Use modern CSS and valid markup

现代 CSS 的使用减少了标记量,在布局方面可以减少对(间隔)图片的需求,并且经常可以替换风格化文本的图片 - 这比同等的文本和 CSS 更有效。

¥Use of modern CSS reduces the amount of markup, can reduce the need for (spacer) images, in terms of layout, and can very often replace images of stylized text — that "cost" much more than the equivalent text-and-CSS.

使用有效的标记还有其他优点。首先,浏览器在解析 HTML 时无需执行纠错(这不包括是否允许用户输入中的格式变化,然后以编程方式 "correct" 或规范化它的哲学问题;或者是否强制执行严格的格式)。 ,无公差输入格式)。

¥Using valid markup has other advantages. First, browsers will have no need to perform error-correction when parsing the HTML (this is aside from the philosophical issue of whether to allow format variation in user input and then programmatically "correct" or normalize it; or whether, instead, to enforce a strict, no-tolerance input format).

此外,有效的标记允许免费使用可以预处理网页的其他工具。例如,HTML 整洁 可以删除空格和可选的结束标签;但是,它将拒绝在存在严重标记错误的页面上运行。

¥Moreover, valid markup allows for the free use of other tools that can pre-process your web pages. For example, HTML Tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors.

将你的内容分块

¥Chunk your content

布局表是一种遗留方法,不应再使用。应改用使用 floatspositioningflexboxgrids 的布局。

¥Tables for layouts are a legacy method that should not be used anymore. Layouts utilizing floats, positioning, flexbox, or grids should be used instead.

表格仍被视为有效标记,但应用于显示表格数据。为了帮助浏览器更快地呈现页面,你应该避免嵌套表格。

¥Tables are still considered valid markup but should be used for displaying tabular data. To help the browser render your page quicker, you should avoid nesting your tables.

而不是像下面这样深度嵌套表:

¥Rather than deeply nesting tables as in:

html

<table>
  <table>
    <table></table>


  </table>
</table>

使用非嵌套表或 div,如下所示

¥use non-nested tables or divs as in

html

<table></table>




<table></table>




<table></table>


也可以看看:CSS 弹性框布局CSS 网格布局 规范。

¥See also: CSS flexible box layout and CSS grid layout specifications.

缩小和压缩 SVG 资源

¥Minify and compress SVG assets

大多数绘图应用生成的 SVG 通常包含可以删除的不必要的元数据。配置你的服务器,对 SVG 资源应用 gzip 压缩。

¥SVG produced by most drawing applications often contains unnecessary metadata which can be removed. Configure your servers, apply gzip compression for SVG assets.

缩小并压缩你的图片

¥Minify and compress your images

大图片会导致页面加载时间更长。在将图片添加到页面之前,请考虑使用图片处理工具(例如 Photoshop)中内置的压缩功能或使用专用工具(例如 压缩 Jpeg小 PNG)对其进行压缩。

¥Large images cause your page to take more time to load. Consider compressing your images before adding them to your page, using compression features built into image-manipulation tools such as Photoshop, or using a specialized tool such as Compress Jpeg or Tiny PNG.

指定图片和表格的尺寸

¥Specify sizes for images and tables

如果浏览器可以立即确定图片和表格的高度和/或宽度,则它将能够显示网页,而无需重新排列内容。这不仅可以加快页面的显示速度,还可以防止页面完成加载时页面布局发生令人讨厌的更改。因此,应尽可能为图片指定 heightwidth

¥If the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. This not only speeds the display of the page but prevents annoying changes in a page's layout when the page completes loading. For this reason, height and width should be specified for images, whenever possible.

表格应使用 CSS 选择器:属性组合:

¥Tables should use the CSS selector: property combination:

css
table-layout: fixed;

并且应该使用 <col><colgroup> 元素指定列的宽度。

¥and should specify widths of columns using the <col> and the <colgroup> elements.

对图片使用延迟加载

¥Use lazy loading for images

默认情况下,图片会立即加载;也就是说,图片在 HTML 中经过处理后就会立即获取并呈现。所有预加载的图片都会在发送窗口的 load 事件之前呈现。切换到延迟加载图片会告诉浏览器推迟加载图片,直到需要它们来绘制 visual viewport

¥By default, images are loaded eagerly; that is, the image is fetched and rendered as soon as it's processed in the HTML. All eagerly loaded images are rendered before the window's load event is sent. Switching to lazy loading of images tells the browser to hold off on loading images until they're about to be needed to draw the visual viewport.

要将图片标记为延迟加载,请将其 loading 属性指定为值 lazy。通过此设置,图片只会在需要时才加载。

¥To mark an image for lazy loading, specify its loading attribute with a value of lazy. With this set, the image will only be loaded when it's needed.

html
<img src="./images/footerlogo.jpg" loading="lazy" alt="MDN logo" />

请注意,当触发 load 事件时,延迟加载的图片可能不可用。你可以通过检查其布尔 complete 属性的值是否为 true 来确定是否加载给定图片。

¥Note that lazily-loaded images may not be available when the load event is fired. You can determine if a given image is loaded by checking to see if the value of its Boolean complete property is true.

明智地选择你的用户代理要求

¥Choose your user-agent requirements wisely

为了实现页面设计的最大改进,请确保为项目指定合理的用户代理要求。不要要求你的内容在所有浏览器中都显示像素完美,尤其是在低版本浏览器中。

¥To achieve the greatest improvements in page design, make sure that reasonable user-agent requirements are specified for projects. Do not require your content to appear pixel-perfect in all browsers, especially not in down-version browsers.

理想情况下,你的基本最低要求应基于支持相关标准的现代浏览器的考虑。这可能包括最新版本的 Firefox、Google Chrome、Opera 和 Safari。

¥Ideally, your basic minimum requirements should be based on the consideration of modern browsers that support the relevant standards. This can include recent versions of Firefox, Google Chrome, Opera, and Safari.

但请注意,本文列出的许多技巧都是常识性技术,适用于任何用户代理,并且可以应用于任何网页,无论浏览器支持要求如何。

¥Note, however, that many of the tips listed in this article are common-sense techniques which apply to any user agent, and can be applied to any web page, regardless of browser-support requirements.

如果可能的话,使用异步和延迟

¥Use async and defer, if possible

使 JavaScript 脚本与 asyncdefer 属性兼容,并尽可能使用 async,特别是当你有多个脚本元素时。

¥Make the JavaScript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script elements.

这样,页面就可以在 JavaScript 仍在加载时停止渲染。否则,浏览器将不会渲染不具有这些属性的脚本元素之后的任何内容。

¥With that, the page can stop rendering while JavaScript is still loading. Otherwise, the browser will not render anything that is after the script elements that do not have these attributes.

注意:尽管这些属性在第一次加载页面时确实有很大帮助,但你应该使用它们,但不要假设它们适用于所有浏览器。如果你已经遵循所有 JavaScript 最佳实践,则无需更改你的代码。

¥Note: Even though these attributes do help a lot the first time a page is loaded, you should use them but not assume they will work in all browsers. If you already follow all JavaScript best practices, there is no need to change your code.

页面结构示例

¥Example page structure

  • <html>
    • <head>
      • <link> 页面外观所需的 CSS 文件。最大限度地减少文件数量以提高性能,同时将不相关的 CSS 保留在单独的文件中以进行维护。
      • <script> JavaScript 文件用于页面加载期间所需的功能,但不是任何只能在页面加载后运行的与交互相关的 JavaScript 文件。 最大限度地减少文件数量以提高性能,同时将不相关的 JavaScript 保留在单独的文件中以进行维护。
    • <body> 用户可见的页面内容以小块 (<header>/ <main>/ <table>) 的形式显示,无需等待整个页面下载。
      • <script> 将用于执行交互的任何脚本。交互脚本通常只能在页面完全加载并且所有必要的对象都已初始化后运行。无需在页面内容之前加载这些脚本。这只会减慢页面加载的初始速度。 最大限度地减少文件数量以提高性能,同时将不相关的 JavaScript 保留在单独的文件中以进行维护。

也可以看看

¥See also