Home Data Center Series: Uncovering the "eye-catching tricks" of WordPress acceleration: Instant.page's minimalist optimization method

Preface

Originally this week’s article wasn’t about this, but because a friend in the group mentioned using instant.page to optimize WordPress access, I realized that I had never heard of this thing (I admit that I am ignorant, after all, I am a newcomer who has only been in contact with WordPress for a little over a year~), then I looked it up and found that the working principle is quite interesting. I thought about it and I haven’t worked hard on optimizing the blog for a long time, so I installed it and gave it a try. Then I thought that since I have used it, I might as well write about it this week~.

Conventional ways to optimize WordPress access speed

For those who use WordPress to build websites, "optimizing the access speed of WordPress" is an unavoidable challenge. Generally speaking, the conventional optimization methods include the following options:

1. WordPress local optimization options

Cache plugin(such as WP Super Cache)

Static Page Caching: Reduce page loading time by caching dynamically generated pages as static HTML files. Enable the preloading function to generate and cache frequently visited pages in advance before users visit them.

Browser Cache: Set appropriate browser cache headers to ensure that static resources (such as CSS, JS, and images) are cached in the visitor's browser to reduce repeated loading.

Redis database cache

Redis Cache and Object Cache: By using Redis (such as the Redis Object Cache plugin), WordPress's database query results, comments, login status and other dynamic content can be cached to reduce the frequency of database access, increase data retrieval speed, and optimize overall performance.

Persistent Cache Strategy: Configure Redis to retain the validity period and expiration policy of the cache to ensure that the cache can improve performance without expiring too quickly.

Image and media optimization

Image Lazy Loading:Use plugins (such as WP Rocket or LazyLoad) to enable lazy loading, prioritize loading content in the user-visible area, and load the remaining images only when entering the visitor's visible area, reducing the initial loading time (this feature has been enabled by default since WordPress 5.5).

Image Optimization: Compress images through plug-ins (such as ShortPixel, Smush) or manually to reduce image size and increase loading speed.

WebP format: Use WebP format instead of traditional JPEG/PNG format to provide smaller file size.

Database optimization

Regularly optimize the database: Use plugins (such as WP-Optimize) to regularly clean up useless data (such as revisions, spam comments, etc.) to keep the database clean and reduce query time.

Reduce unnecessary queries: Streamline WordPress queries to avoid high-frequency database access caused by plugins or themes.

Minimal plugins and themes

• Disable unnecessary plugins to reduce the impact of plugins on performance. Choose lightweight and well-optimized plugins, and avoid using overly complex or infrequently updated plugins.

• Choose high-performance, well-optimized themes, avoid using excessive JavaScript and CSS, and keep the theme code simple.

2. Optimization selection at the CDN level (taking cloudflare as an example)

Cache rules

Static resource caching:By configuring the cache rules of CDN (such as Cloudflare), the static resources (such as CSS, JS, images, etc.) of the WordPress website can be cached to CDN nodes. This can reduce back-to-source requests, speed up the loading of static resources, and thus improve the overall access speed.

Full page cache:Use CDN to cache the entire page of a WordPress page, and cache the entire page content (except for some non-cached content) to the CDN node, reducing the burden on the server and significantly reducing the response time. This is especially suitable for pages that do not change frequently, such as article pages, static pages, etc.

Cache strategy and fine-grained control:According to the frequency of content updates, set different cache strategies. For static resources that change less frequently (such as images, CSS files, JavaScript files, etc.), you can set a longer cache time; for content that changes frequently (such as pages with user personalized information, user panels, etc.), you should avoid caching or set a shorter cache time to ensure timely updates and accuracy of the content. It should be noted that dynamic content such as comments is usually not suitable for caching, because these contents will change with user interactions and must be generated dynamically.

Edge Cache:By utilizing the edge cache provided by CDN, the data closest to the user's node is cached to improve loading speed. Edge cache improves the stability and speed of website access by reducing the load and response time of the source station. By setting TTL (cache survival time), the cache refresh frequency can be flexibly controlled to ensure the timeliness of cached data.

Worker-related optimization methods

Cloudflare Workers:Cloudflare Workers is an edge computing feature that allows developers to execute custom caching logic on CDN edge nodes. With Workers, you can flexibly adjust caching strategies based on factors such as the user's geographic location, device type, and request language. For example, you can cache different versions of a page based on different user request conditions, or decide whether to cache a request based on real-time data. Workers provides more fine-grained cache control and is suitable for highly customized scenarios.

APO (Automatic Platform Optimization):APO is a dedicated service optimized by Cloudflare for WordPress. It automatically caches WordPress pages (including dynamic content) and accelerates the loading of these pages through Cloudflare's global CDN network. APO automatically handles common caching rules, reduces requests to the origin server, and increases page loading speed. APO is very suitable for most WordPress websites, especially those that require high concurrency processing.

The above are conventional methods for optimizing and accelerating WordPress. However, I have learned about another optimization method these days: instant.page, which uses the "preloading" method (thanks to my friend "tony8077616" for the recommendation). This method "improves" the speed of opening pages when visitors visit WordPress websites from another level. After testing, I think it is very effective, so I use this article to record it.

instant.page and “preloading”

What is "preloading"?

In fact, instant.page (official website:https://instant.page/) is similar to the "delayed loading" mentioned in the "Image and Media Optimization" section of the previous section."Cheating" user feelingsA "smokescreen" to improve the user's "perceived loading speed": it preloads the page by using the "time between mouse hovering and clicking", allowing the page content to be displayed almost instantly when the user clicks, thereby "cheating the brain" (the human brain regards actions that take less than 100 milliseconds as instant operations), making the user feel that the page loads faster, but the actual network loading speed has not changed.


It usually takes a normal person about 300 milliseconds to click a link:

image.png

So theoretically, the "preloading" method can save at least 300 milliseconds.


Technical principle

instant.pageIn fact, it is just an independent JavaScript code. Its main function is to listen to the user's mouse hover event and load the target page content in advance, thereby significantly shortening the waiting time for the page to load after the user clicks. It does not rely on any specific platform or CMS, but is optimized based on the common interactive behavior of the web page (such as mouse hover). On a touch screen device, this process corresponds to the time period from when the user touches the link to when the finger leaves the screen. The technical principle is as follows:

  1. Listening for mouse hover events: When a user hovers over a link, instant.page captures this action.
  2. Preload the target page: instant.page will use fetch() request to preload the resources (such as HTML, CSS, JavaScript, etc.) of the target page corresponding to the link where the mouse is hovering.
  3. Prepare content in advance: These preloaded resources are cached or stored in memory by the browser so that when the user clicks the link, the page is displayed almost instantly.

Relationship between instant.page and conventional optimization methods

Instant.pageAlthough it is a tool that preloads page resources based on user behavior, it is not an independent performance optimization method. Instead, it relies on the traditional WordPress optimization methods mentioned above. Only after completing these traditional optimizations can Instant.page really play its advantages. For example:

1. WordPress local optimization and Instant.page collaboration

Static page caching and browser caching

Instant.page Dependencies:When a user browses a page, Instant.page will load the static HTML file of the target link to the browser through preloading. If static page caching is enabled (such as the function provided by WP Super Cache), Instant.page can directly load the cached static page instead of requesting dynamically generated pages, thereby significantly reducing server load and response time.

Enhanced effect: When the browser cache is set up properly, the preload request of Instant.page will obtain static resources such as CSS and JS from the user's browser cache without having to load them from the server or CDN. This further speeds up page loading.

Redis database cache

Instant.page Dependencies: Instant.page cannot directly optimize WordPress's dynamic queries, but if Redis has cached the database query results, Instant.page's preload request will trigger Redis's quick response instead of directly accessing the database.

Enhanced effect: Through the object cache provided by Redis, dynamic content (such as comments or login status) can also be responded to quickly, avoiding database performance bottlenecks caused by preloading of Instant.page.

Image and Media Optimization

Instant.page Dependencies:Instant.page preloading triggers the loading of image resources. If lazy loading is enabled and an optimized image format (such as WebP) is used, the preloaded image resources will be smaller and faster.

Enhanced effect: By compressing images through plugins such as ShortPixel or Smush, Instant.page preload requests will take up less bandwidth and increase loading speed.

2. CDN-level optimization and collaboration with Instant.page

CDN is an important tool for improving the performance of WordPress websites. Its caching capabilities and edge computing support can significantly reduce the pressure of returning to the source and accelerate page loading. The preloading function of Instant.page can make full use of the advantages of CDN and directly read from the CDN node when the resources have been cached, further improving the access speed.

Static resource caching

Instant.page Dependencies:Use CDNs such as Cloudflare to cache static resources (such as CSS, JS, images, etc.) to the CDN nodes closest to the user. Instant.page preload requests will prioritize obtaining resources from these nodes to reduce latency.

Enhanced effect: Reasonably set the cache strategy for static resources (such as caching infrequently changing resources for a long time), and the preloading of Instant.page can respond quickly and significantly reduce server load and network latency.

Full page cache

Instant.page Dependencies:The full page cache function of CDN (such as Cloudflare's APO) will cache the entire page to the edge node. In this case, the preload request of Instant.page does not require the server to generate the page content, but directly loads the cached HTML page.

Enhanced effect: For article pages or other content that is updated less frequently, full-page caching can be used in conjunction with Instant.page to achieve near-instant loading speeds.

Edge caching and edge computing

Instant.page Dependencies:Through Edge Cache, CDN can cache the content that users have recently accessed to nodes close to the users. Instant.page preloading will load resources directly from edge nodes without going back to the source server.

Enhanced effect:Using edge computing tools such as Cloudflare Workers, more flexible cache control can be achieved. For example, loading specific resources based on user device, geographic location or language, Instant.page's preloading function can trigger these targeted optimizations.

Cloudflare Workers and custom optimizations

Instant.page Dependencies:Cloudflare Workers allows running custom logic on edge nodes. For example, dynamically generating different versions of page caches or handling special request conditions, Instant.page preloading can directly cooperate with these custom cache logic.

Enhanced effect: Through Workers, preloading can provide highly personalized content for different user requests, further improving loading speed and user experience.

APO (Automatic Platform Optimization)

Instant.page Dependencies:Cloudflare's APO is optimized for WordPress, reducing server burden by automatically caching pages and static resources. Instant.page preloading is perfectly integrated with APO, and can directly load optimized content.

Enhanced effect: Especially in high-concurrency scenarios, APO provides stable cache response capabilities to ensure that the preloading of Instant.page will not fail due to server pressure or dynamic generation bottlenecks.

Cache refinement for dynamic content

Instant.page Dependencies:For dynamic content (such as comments, user panels, etc.), the refinement of caching strategies is crucial. For example, using Workers or other tools to dynamically generate non-cacheable parts of the content, the preload request of Instant.page can trigger precisely controlled dynamic loading logic.

Enhanced effect:This optimization can take into account the real-time nature of dynamic content and the loading speed of static content, making the preloading of Instant.page compatible with complex scenarios.

In general, CDN's cache and optimization functions provide a solid foundation for Instant.page: by properly configuring static resource cache, full page cache, edge cache, and using advanced features such as Workers and APO, Instant.page's preloading can respond to user requests more efficiently and significantly reduce server pressure. More importantly, the synergy of these optimization measures maximizes the acceleration effect of Instant.page, allowing the user experience to truly achieve "click-and-see".

Deploy instant.page

I talked about the principle in a long-winded way, but it is very simple to actually deploy instant.page, because it is essentially just a piece of js code, and there are many ways to deploy this code.

Deploy on WordPress

How to use plugins

If you are deploying on WordPress, the easiest way is to use a plugin. You only need to install the instant.page plugin directly:

image.png

The Anhaohao plugin can be enabled directly without any additional settings:
image.png

Directly quote the script address provided by the official

Just change the following code:

<script src="//instant.page/5.2.0" type="module" integrity="sha384-jnZyxPjiipYXnSU0ygqeac2q7CVYMbh84q0uHVRRxEtvFPiQYbXWUorga2aqZJ0z"></script>

Insert into wordpress's footer.php file</body>Before (conventional HTML static pages can also be directly inserted</body>Before).

Note: This method requires the client browser to be able to load normallyhttps://instant.page/5.2.0This is the official script address.

Load local js script

This method requires you to put the "instantpage.js" script in the local WordPress path first. It is recommended to put it in the wp-content subdirectory, for example:

wp-content/js/instantpage.js

Then, as before, in the footer.php file/<body>Just insert the following code before:

<script src="/wp-content/js/instantpage.js" type="module"></script>

For the instantpage.js file, you can find it on the homepage of instant.page on GitHub (instant.page github homepage) to see the latest version of the script, or get it directly from the address provided by the official website (https://instant.page/5.2.0):

image.png

However, the version on GitHub is newer, so if you want to use it, try to use the version on GitHub. For those who cannot access GitHub, you can also download it from my "Blog File Sharing Special Link" (https://fileshare.tangwudi.com/s/file, share password: blog.tangwudi.com), as shown below:

image.png

High-end version: based on cloudflare worker

This method not only allows you to avoid installing plugins in the website built by WordPress (or directly introduce the instant.page script in the footer.phpo file), but also more efficiently utilize Cloudflare's global edge network to distribute and execute scripts. If your website uses dynamically generated HTML pages (such as WordPress), this method is particularly suitable. For specific steps to create a worker, please refer to the article:Home Data Center Series Cloudflare Tutorial (VII) Introduction to CF Worker Functions and Practical Operation, Verification and Research on Related Technical Principles of Implementing "Beggar Version APO for WordPress" Function to Accelerate Website Access Based on Worker.

The contents of the worker script are as follows:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // 检查是否为 HTML 页面
  if (url.pathname.endsWith('.html') || url.pathname === '/') {
    const response = await fetch(request);
    const contentType = response.headers.get('content-type') || '';

    // 只对 HTML 类型的响应注入 instant.page 脚本
    if (contentType.includes('text/html')) {
      const text = await response.text();
      const modifiedBody = text.replace(
        '</body>',
        `<script src="//instant.page/5.2.0" type="module" defer integrity="sha384-jnZyxPjiipYXnSU0ygqeac2q7CVYMbh84q0uHVRRxEtvFPiQYbXWUorga2aqZJ0z"></script></body>`
      );
      return new Response(modifiedBody, {
        headers: response.headers,
        status: response.status,
        statusText: response.statusText,
      });
    }
  }

  // 对非 HTML 请求保持原样
  return fetch(request);
}

If you want to verify whether the worker method is successful, you can use the browser's developer tools to view the HTML page source code of the site and confirm<script src="https://instant.page/5.2.0"...> Has it been correctly injected into <body> At the end of the tag, if yes, it means the configuration is successful.

Note 1: The double slashes in //instant.page are kept to support protocol-relative loading, which automatically adapts to http or https.

Note 2: If you need to use another version in the future, just update the version number and the corresponding integrity value.

Note 3: Since Cloudflare Workers has a lower priority in the traffic sequence, it will only take effect when other functional modules do not process or intercept the request. Therefore, in order to ensure that the Worker script can run normally and achieve the expected effect, please properly configure the functional modules with higher priority, such as "Page Rules", "Cache Rules" orWAFEtc. For details about "traffic sequence", please refer to the article:Cloudflare tutorial series for home data centers (Part 2) Introduction to the functions of each technical node in the CF overall solution traffic sequence.

注4:使用 Cloudflare Workers可能涉及额外费用(免费计划每天有100,000 次请求的限制,超过之后默认行为是拒绝访问,当然也可以改为超过限制后直接回源~),请根据网站实际的访问率进行评估。

Verify the "preloading" effect of instant.page

It’s easy to verify that instant.page’s “preloading” is working, just use your browser’s developer tools.

First find a page, for example, I use the "AI Learning Map" of my blog:

image.png

The link in the red box above is used as a test link, and then open the browser's developer tools (I use Chrome):
image.png

Then move the mouse over the links of the six articles from top to bottom, and observe the network log recorded in the developer tools on the right:
image.gif

You can see that the "preload" effect is effective.

Besides "deception", is there "true love"?

Preloading can also shorten the overall page loading time

Although "preloading" can "trick" visitors' brains into thinking that access speed is improved, is it really of no help in shortening the actual loading time of the entire page?

In fact, Instant.page can actually shorten the loading time of web pages in some cases, rather than just "tricking" the visitor's brain. Although its core mechanism "preloading" aims to improve the user experience and give people a "faster" feeling, it does not mean that it has no effect on the actual loading time in any scenario. Here are a few situations where it can help shorten the loading time:

1. Latency Reduction

Instant.page's preloading mechanism will actively load the target page's resources when the user hovers over the link. Because the request to load resources is issued in advance, it can significantly reduce the time users wait for the server to respond after clicking the link.

Applicable scenarios: A website with slow server response in a high-latency network environment.

Actual Results: When a user clicks a link, the resources of the target page may have been loaded or partially loaded, thus reducing the time required for subsequent loading.

2. Make full use of bandwidth idle time

Instant.page uses the short time between clicks (mouseover or pauses for touchscreen users) when the network is usually idle to send preload requests.

Applicable scenarios: A network environment with sufficient bandwidth.

Actual Results:These resources have been loaded or cached before the user clicks the link, so there is no need to repeat the request when the page loads, which actually speeds up the page loading.

3. Integration with caching mechanism

Instant.page's preloading mechanism can better cooperate with caching strategies (such as CDN and browser cache) to load resources in advance, thereby improving the page loading experience.

CDN Cache:When the target page's resources have been cached in the CDN node, the Instant.page preload request will also directly obtain the resources from the CDN, thus avoiding unnecessary back-to-origin requests. Although this is essentially the same as directly clicking to request resources, preloading can complete resource loading earlier by triggering the request in advance.

Browser Cache:The preload request of Instant.page will store the target resource in the browser cache. When the user officially visits the page, the browser can directly call the cached resource to avoid re-initiating the request, thereby reducing the loading time.

Applicable scenarios:The website has enabled an effective caching strategy (such as long-term caching rules for static resources); resources are distributed through CDN, and there is low latency between the user's network and the CDN node.

Actual Results: Instant.page completes the loading or partial loading of resources in advance, shortening the loading time after the user clicks; the browser cache mechanism further reduces repeated requests and optimizes the loading efficiency of the page.

4. Rapid pre-generation of dynamic content

For dynamic content (such as personalized pages), if the website cooperates with server-side technology (such as Redis cache or Cloudflare Workers) to trigger content generation when the user preloads, Instant.page can indirectly optimize the page generation time.

Applicable scenarios: Dynamic page loading for websites that require generated content.

Actual Results:Dynamic content has been generated and can respond quickly before the user formally requests the page.

5. Reduce Time to First Byte (TTFB)

Through the advance request of Instant.page, the browser and server can complete the establishment of TCP connection, SSL handshake and initial resource acquisition in advance, thereby shortening the TTFB of the page.

Applicable scenarios: Sites with long TTFB.

Actual Results: A reduction in time to first byte directly reduces overall load time.

6. Improve the first screen loading speed

Instant.page focuses on preloading key resources (such as HTML files) of the target page, which allows the first screen content to be presented faster when users enter a new page.

Applicable scenarios:The first screen rendering time has high requirements on the user experience of the website.

Actual Results: Even though non-critical resources still need to be loaded, the user perceives the first screen to be presented faster, and the actual page load time is shortened.

In summary, although the mechanism of Instant.page is to improve the perceived speed by "deceiving" the visitor's brain, it is not completely unable to shorten the actual loading time. In certain scenarios, it has a practical impact on the web page loading time in the following ways:

• Initiate resource requests in advance to reduce latency.

• Utilize idle bandwidth to improve resource loading efficiency.

• Use caching strategies or dynamic generation mechanisms to optimize loading performance.

However, the effectiveness of these effects is highly dependent on the basic optimization of the website (such as caching strategy, CDN deployment, etc.). If the website is not optimized (for example, there is no CDN or caching strategy), the actual help of Instant.page will be greatly reduced, and it will only remain at the level of "perceived speed improvement".

How to verify the above conclusions?

Originally, I wanted to use Google's website speed test "PageSpeed Insights" to verify the conclusion drawn in the previous section: instant.page can shorten the actual loading time in certain scenarios. But the key problem is that even if I use "PageSpeed Insights" to test normally twice in a row, the score results may be very different, such as the test results this time:

first:

image.png

Second time:

image.png

Therefore, it is impossible to directly judge the effect from the score. It seems that we need to focus on the numerical changes of these five key parameters: First Contentful Paint (FCP), Largest Contentful Paint (LCP), Total Blocking Time, Cumulative Layout Shift (CLS), and Speed Index.

However, in theory, the "preloading" of instant.page is not effective for every parameter, so we need to first sort out the impact of preloading on each parameter in theory:

1. First Contentful Paint (FCP)

definition: The time when the page first renders visible content.

• instant.page Impact: Significant optimization. Preloading obtains key resources (such as HTML, CSS) in advance, allowing the page to start rendering content faster.

2. Largest Contentful Paint (LCP)

definition: Rendering time of the largest visible content of the page.

• instant.page Impact: Significant optimization. Key resources (such as images or main text blocks) are loaded in advance, reducing waiting time and thus shortening LCP.

3. Total Blocking Time (TBT)

definition: The total time the main thread is blocked by long tasks.

• instant.page Impact: No significant impact. The preloading mechanism will not reduce the parsing and execution time of JavaScript, but preloading resources may indirectly reduce some of the blocking related to resource loading.

4. Cumulative Layout Shift (CLS)

definition: Stability of layout during page loading.

• instant.page Impact: No significant impact. Preloading does not directly interfere with layout changes, but if resources are loaded in advance (such as fonts or images), it may indirectly reduce layout jitter caused by resource loading delays.

5. Speed Index

definition: How quickly visible content is displayed during page loading.

• instant.page Impact: Significant optimization. Preloading resources enables the page to display visible content faster, thus improving Speed Index.

Performance Indicators instant.page The optimization effect Impact Analysis
First Contentful Paint (FCP) Significant Optimization Load resources ahead of time to speed up first content rendering time.
Largest Contentful Paint (LCP) Significant Optimization Critical resources are loaded ahead of time, allowing the largest chunks of content to render faster.
Total Blocking Time (TBT) No significant effect It does not interfere with the main thread tasks and only indirectly reduces the blocking caused by some resource loading.
Cumulative Layout Shift (CLS) No significant effect It has a weak relationship with layout changes, but it indirectly reduces the jitter caused by some resource delays.
Speed Index Significant Optimization Resource preloading improves the consistency and speed of page display.

Precautions:
1. FCP and LCP This is the most influential indicator of instant.page and is suitable for scenarios where you need to speed up the loading of the first screen and main content.
2. If optimization is needed TBT and CLS, needs to be combined with other means (such as optimizing JavaScript and avoiding layout thrashing).

Practical verification

Note: To do this experiment, I had to disable the instant.page plugin, clear all cache on cloudflare, and run "PageSpeed Insights" once. Then I enabled instant.page, cleared all cache on cloudflare, and ran "PageSpeed Insights" again. I sacrificed a lot for science.

Results of disabling instant.page:

image.png

The result of enabling instant.page:

image.png

Well, it feels like the differences are all within a reasonable error range. It seems that the results of this test cannot verify the conclusions of the previous section. The experiment failed. It feels like this is because after using Cloudflare's CDN, there are many additional factors in the test process. It should be more intuitive without CDN, but I really don't have the energy to bother with it anymore.

“注销”、”退出”按钮的特殊处理

采用instant.page实现预加载功能之后,有一个问题,就是鼠标划过”注销”、”退出”按钮时就直接执行了,这时候登录用户本身可能还未意识到这个问题,执行一些需要登录的操作就会报错。

那么,在WordPress中如何优化这个问题呢?以下是优化方法的几种思路供大家参考:

1. 排除敏感链接的预加载

方法:利用 data-no-instant 属性

在 WordPress 中,“注销” 和其他敏感链接通常由主题或插件生成。可以通过以下方式添加 data-no-instant:

a. 修改主题模板文件

找到生成这些链接的模板代码(如 wp_nav_menu() 或其他生成菜单的代码),并手动添加 data-no-instant。

示例代码:

<?php
wp_nav_menu(array(
    'theme_location' => 'primary',
    'items_wrap'     => '<ul id="%1s" class="%2s">%3s</ul>',
    'walker'         => new class extends Walker_Nav_Menu {
        public function start_el(&output, item,depth = 0, args = null,id = 0) {
            output .= sprintf(
                '<li><a href="%s"%s>%s</a></li>',
                esc_url(item->url),
                (strpos(item->url, '/logout') !== false) ? ' data-no-instant' : '',
                esc_html(item->title)
            );
        }
    }
));
?>

b. 通过 WordPress 钩子动态添加

如果使用默认的菜单生成函数,可以通过 wp_nav_menu_items 或 wp_get_nav_menu_items 钩子动态修改链接属性:

add_filter('wp_nav_menu_items', function(items) {
    return preg_replace('/href=["\'](.*logout.*)["\']/', 'href="1" data-no-instant', $items);
});

2. 利用 JavaScript 动态阻止

在 WordPress 中,您可以将这部分逻辑写入主题的自定义 JavaScript 文件或通过插件添加。例如:

方法:通过 wp_enqueue_script 添加脚本

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script('disable-preload', get_template_directory_uri() . '/js/disable-preload.js', [], null, true);
});

disable-preload.js 示例内容:

document.querySelectorAll('a[href*="logout"]').forEach(link => {
    link.setAttribute('data-no-instant', '');
});

3. 使用 JavaScript 验证行为

在 WordPress 中,可以为敏感链接(如 “注销”)添加确认弹窗或额外验证。这适用于通过插件或主题生成的按钮或链接。

方法:添加确认弹窗

在模板文件中,为特定链接添加 onclick 属性:

<a href="/en/</?php echo wp_logout_url(); ?>" onclick="return confirm('确定要注销吗?');">注销</a>

或者通过全局脚本动态添加:

document.querySelectorAll('a[href*="logout"]').forEach(link => {
    link.addEventListener('click', function(e) {
        if (!confirm('确定要注销吗?')) {
            e.preventDefault();
        }
    });
});

4. 后端逻辑优化

WordPress 提供了丰富的过滤器和动作,可以在后端拦截请求。例如:

方法:判断预加载请求

可以通过 PHP 检测预加载的请求头(如 X-Instant-Page),并避免执行敏感操作。

add_action('wp_logout', function() {
    if (!empty($_SERVER['HTTP_X_INSTANT_PAGE'])) {
        wp_die('此操作无法通过预加载完成,请重新点击注销按钮。');
    }
});

5. 配置 Instant.page 选项

在 WordPress 中,您可以通过以下方式更细粒度地控制 Instant.page 的行为:

方法:配置加载参数

将 Instant.page 脚本加入主题或插件,并设置参数:

add_action('wp_enqueue_scripts', function() {
    wp_enqueue_script('instantpage', 'https://cdn.instant.page/5.1.0', [], null, true);
    wp_add_inline_script('instantpage', '{mousedown: true, mouseover: 200}');
});

以上这些操作可以有效避免短暂悬停时就触发预加载,大家可以根据自己的实际情况选择最适合自己的优化方式。

注:感谢小伙伴”秋风于渭水”在评论区的提醒。

Afterword

I originally wanted to write an article to get by for a week, but I didn't expect to go through so much trouble. However, from the perspective of WordPress optimization, I think instant.page is still worth my trouble. After all, it is quite interesting to optimize the access experience of WordPress from another level. The key is that it is easy to deploy, just a few lines of code or a plug-in. I recommend friends who use WordPress to try it.

The content of the blog is original. Please indicate the source when reprinting! For more blog articles, you can go toSitemapUnderstand. The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if necessary, you can joinTelegram GroupDiscuss the problem together.

Comments

  1. Windows Chrome 131.0.0.0
    3 weeks ago
    2025-1-13 10:35:26

    顺带提一嘴如果想要自行实现,请一定把【注销】【退出】等链接给排除了,不然会出现鼠标不小心划过【退出登录】按钮,WP登录状态就无了。曾经因此有过非常惨痛的排障过程,找了一大圈才发现是预加载的锅。

    • tangwudi
      Autumn Wind on Weishui River
      iPhone Chrome 131.0.6778.154
      3 weeks ago
      2025-1-13 11:57:58

      感谢,这提醒很重要,回头我补充到文章里去,我博客目前禁用了注册,到是不会遇到这问题,但是其他允许注册博客的博主的确需要重视这问题。

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠(ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ°Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Emoticons
Emoji
Little Dinosaur
flower!
Previous
Next
       
error:
en_US
Spring Festival
hapiness