htmx 预加载扩展

preload 扩展允许你在用户请求 HTML 片段之前将其加载到浏览器的缓存中,这样用户就会看到其他页面几乎可以立即加载。作为开发者,你可以自定义其行为以满足你的应用需求和用例。

¥The preload extension allows you to load HTML fragments into your browser’s cache before they are requested by the user, so that additional pages appear to users to load nearly instantaneously. As a developer, you can customize its behavior to fit your applications needs and use cases.

重要:明智地预加载内容可以提高 Web 应用的感知性能,但预加载过多资源会启动过多未使用的请求,从而对访问者的带宽和服务器性能产生负面影响。请谨慎使用此扩展!

¥IMPORTANT: Preloading content judiciously can improve your web application’s perceived performance, but preloading too many resources can negatively impact your visitors’ bandwidth and your server performance by initiating too many unused requests. Use this extension carefully!

安装

¥Installing

安装 preload 的最快方法是通过 CDN 加载它。请记住始终在扩展和 启用扩展 之前包含核心 htmx 库。

¥The fastest way to install preload is to load it via a CDN. Remember to always include the core htmx library before the extension and enable the extension.

<head>
    <script src="https://unpkg.com/htmx.org@2.0.4" integrity="sha384-HGfztofotfshcF7+8n44JQL2oJmowVChPTg48S+jvZoztPfvwD79OC/LTtG6dMp+" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/htmx-ext-preload@2.1.0" integrity="sha384-fkzubQiTB69M7XTToqW6tplvxAOJkqPl5JmLAbumV2EacmuJb8xEP9KnJafk/rg8" crossorigin="anonymous"></script>
</head>
<body hx-ext="preload">
...

https://unpkg.com/htmx-ext-preload/dist/preload.js 上还有一个未缩小的版本。

¥An unminified version is also available at https://unpkg.com/htmx-ext-preload/dist/preload.js.

虽然 CDN 方法很简单,但你可能需要考虑 在生产中不使用 CDN。安装 preload 的下一个最简单的方法是将其复制到你的项目中。从 https://unpkg.com/htmx-ext-preload 下载扩展,将其添加到项目中的相应目录中,并在必要时使用 <script> 标签将其包含在内。

¥While the CDN approach is simple, you may want to consider not using CDNs in production. The next easiest way to install preload is to simply copy it into your project. Download the extension from https://unpkg.com/htmx-ext-preload, add it to the appropriate directory in your project and include it where necessary with a <script> tag.

对于 npm 样式的构建系统,你可以通过 npm 安装 preload

¥For npm-style build systems, you can install preload via npm:

npm install htmx-ext-preload

安装后,你需要使用适当的工具来打包 node_modules/htmx-ext-preload/dist/preload.js(或 .min.js)。例如,你可以将扩展与来自 node_modules/htmx.org/dist/htmx.js 的 htmx 核心和项目特定代码打包在一起。

¥After installing, you’ll need to use appropriate tooling to bundle node_modules/htmx-ext-preload/dist/preload.js (or .min.js). For example, you might bundle the extension with htmx core from node_modules/htmx.org/dist/htmx.js and project-specific code.

如果你使用打包器来管理你的 javascript(例如 Webpack、Rollup):

¥If you are using a bundler to manage your javascript (e.g. Webpack, Rollup):

import `htmx.org`;
import `htmx-ext-preload`; 

使用

¥Usage

使用 hx-ext 属性向 htmx 注册扩展。然后,将 preload 属性添加到要预加载的任何超链接和 hx-get 元素。默认情况下,资源将在 mousedown 事件开始时立即加载,从而使你的应用在服务响应方面领先大约 100-200 毫秒。有关其他选项,请参阅下面的配置。

¥Register the extension with htmx using the hx-ext attribute. Then, add a preload attribute to any hyperlinks and hx-get elements you want to preload. By default, resources will be loaded as soon as the mousedown event begins, giving your application a roughly 100-200ms head start on serving responses. See configuration below for other options.

<body hx-ext="preload">
<h1>What Works</h2>
    <a href="/server/1" preload>WILL BE requested using a standard XMLHttpRequest() and default options (below)</a>
    <button hx-get="/server/2" preload>WILL BE requested with additional htmx headers.</button>

    <h1>What WILL NOT WORK</h1>
    <a href="/server/3">WILL NOT be preloaded because it does not have an explicit "preload" attribute</a>
    <a hx-post="/server/4" preload>WILL NOT be preloaded because it is an HX-POST transaction.</a>
</body>

所有预加载请求都包含一个额外的 "HX-Preloaded": "true" 标头。

¥All preload requests include an additional "HX-Preloaded": "true" header.

继承预加载设置

¥Inheriting Preload Settings

你可以将 preload 属性添加到包含多个 <a href="">hx-get="" 元素的顶层元素,并且所有这些元素都将被预加载。请谨慎使用此设置,因为如果你预加载的资源比你需要的多得多,最终可能会浪费带宽。

¥You can add the preload attribute to the top-level element that contains several <a href=""> or hx-get="" elements, and all of them will be preloaded. Be careful with this setting, because you can end up wasting bandwidth if you preload many more resources than you need.


<body hx-ext="preload">
<ul preload>
    <li><a href="/server/1">This will be preloaded because of the attribute in the node above.</a>
    <li><a href="/server/2">This will also be preloaded for the same reason.</a>
    <li><a href="/server/3">This will be preloaded, too. Lorem ipsum.</a>
</ul>
</body>

预加载表单

¥Preloading Forms

如果表单包含 hx-get 属性或使用 method="get",则扩展可以预加载某些表单元素。preload 属性可以添加到表单或其选定的某些元素中。目前可以预加载以下表单元素:

¥The extension can preload some form elements if the form includes hx-get attribute or uses method="get". The preload attribute can be added to the form or to some of its selected elements. Currently these form elements can be preloaded:

预加载链接图片

¥Preloading of Linked Images

预加载 HTML 页面(或页面片段)后,此扩展还可以预加载链接的图片资源。它不会加载或运行链接的 Javascript 或层叠样式表内容,无论是链接的还是嵌入在预加载的 HTML 中的。要预加载图片,请使用以下语法。

¥After an HTML page (or page fragment) is preloaded, this extension can also preload linked image resources. It will not load or run linked Javascript or Cascading Stylesheet content, whether linked or embedded in the preloaded HTML. To preload images as well, use the following syntax.


<div hx-ext="preload">
    <a href="/my-next-page" preload="mouseover" preload-images="true">Next Page</a>
</div>

配置

¥Configuration

此扩展的默认值选择是为了平衡用户感知的性能与未使用的请求对服务器的潜在负载。作为开发者,你可以修改两个设置以根据你的特定用例自定义此行为。

¥Defaults for this extension are chosen to balance users’ perceived performance with potential load on your servers from unused requests. As a developer, you can modify two settings to customize this behavior to your specific use cases.

preload=“mousedown”(默认)

¥preload=“mousedown” (DEFAULT)

此扩展的默认行为是在用户按下鼠标时开始加载资源。这是一个保守的设置,可保证用户确实打算使用链接的资源。由于用户点击事件通常需要 100-200 毫秒才能完成,因此与常规点击相比,此设置为你的服务器提供了显着的领先优势。

¥The default behavior for this extension is to begin loading a resource when the user presses the mouse down. This is a conservative setting that guarantees the user actually intends to use the linked resource. Because user click events typically take 100-200ms to complete, this setting gives your server a significant headstart compared with a regular click.

<a href="/server/1" preload="mousedown">This will be preloaded when the user begins to click.</a>

preload=“mouseover”

要更积极地预加载链接,你可以在用户的​​鼠标悬停在链接上时触发预加载。为了防止在用户滚动或将鼠标移动到大量对象上时加载许多资源,此操作内置了 100 毫秒的延迟。如果用户的鼠标在此超时到期之前离开元素,则不会预加载资源。

¥To preload links more aggressively, you can trigger the preload to happen when the user’s mouse hovers over the link instead. To prevent many resources from being loaded when the user scrolls or moves the mouse across a large list of objects, a 100ms delay is built in to this action. If the user’s mouse leaves the element before this timeout expires, then the resource is not preloaded.

通常,用户在点击链接之前会将鼠标悬停在链接上数百毫秒,这比上面的 mousedown 选项为你的服务器提供了更多的时间来响应请求。在此测试你自己的悬停时间。。但是,使用此选项时要小心,因为它可能会通过不必要地请求资源来增加服务器负载。

¥Typical users hover over links for several hundred milliseconds before they click, which gives your server even more time to respond to the request than the mousedown option above. Test your own hover timing here.. However, be careful when using this option because it can increase server load by requesting resources unnecessarily.

<a href="/server/1" preload="mouseover">This will be preloaded when the user's mouse remains over it for more than
    100ms.</a>

preload=“custom-event-name”

Preload 还可以监听系统内的任何自定义事件,触发资源预加载(如果它们尚未被浏览器缓存)。扩展本身会生成一个名为 preload:init 的事件,可用于在对象被 htmx 处理后立即触发预加载。

¥Preload can also listen to any custom event within the system, triggering resources to be preloaded (if they have not already been cached by the browser). The extension itself generates an event called preload:init that can be used to trigger preloads as soon as an object has been processed by htmx.


<body hx-ext="preload">
<button hx-get="/server" preload="preload:init" hx-target="idLoadMore">Load More</a>
    <div id="idLoadMore">
        Content for this DIV will be preloaded as soon as the page is ready.
        Clicking the button above will swap it into the DOM.
    </div>
</body>

preload=“always”

默认情况下,扩展将预加载每个元素一次。如果你希望始终保持预加载元素,可以添加 preload="always" 属性。如果 hx-target 不是元素本身,这将很有用。此属性可以与其他配置属性(例如 preload="always mouseover")结合使用。

¥By default, the extension will preload each element once. If you would like to keep always preloading the element, you can add preload="always" attribute. This can be useful if hx-target is not the element itself. This attribute can be combined with other configuration attributes e.g. preload="always mouseover".

关于触摸事件

¥About Touch Events

为了适应触摸屏设备,每当你指定 mouseovermousedown 触发器时,都会添加额外的 ontouchstart 事件处理程序。每当用户触摸屏幕时,此额外触发器都会立即触发(无等待期),在 Android 上为你节省 300 毫秒的等待时间,在 iOS 上为你节省 450 毫秒的等待时间。

¥To accommodate touchscreen devices, an additional ontouchstart event handler is added whenever you specify a mouseover or mousedown trigger. This extra trigger fires immediately (no waiting period) whenever the user touches the screen, saving you 300ms of waiting time on Android, and 450ms on iOS.

限制

¥Limitations

致谢

¥Credits

此插件的行为受到 Alexandre DieulotInstantClick 上所做的工作的启发,该插件根据 MIT 许可证发布。

¥The behavior for this plugin was inspired by the work done by Alexandre Dieulot on InstantClick, which is released under the MIT license.