Preface
Originally, this week's article wasn't going to be about this. However, because a member in our group mentioned using instant.page to optimize WordPress access, I realized I had surprisingly never heard of this thing (I admit I was being ignorant, after all, I'm just a newbie who has only been using WordPress for just over a year~). After looking it up, I found its working principle quite interesting. Realizing that I hadn't put much effort into optimizing my blog for a long time, I installed it to give it a try. Then I thought, since I'm already using it, I might as well just write about this this week~.
Conventional ways to optimize WordPress access speed
For friends who build websites using WordPress, ”optimizing WordPress access speed” is an unavoidable challenge. Generally speaking, conventional optimization methods include the following options:
WordPress local-level optimization options
Cache plugins(such as WP Super Cache)
• Static page caching: By caching dynamically generated pages as static HTML files, page loading time is reduced. Enabling the preloading feature allows frequently visited pages to be generated and cached in advance before users visit.
• Browser caching: Set appropriate browser cache headers to ensure static resources (such as CSS, JS, images) are cached in the visitor's browser, reducing repeated loading.
Redis database caching
• Redis caching and object caching: By using Redis (such as the Redis Object Cache plugin), dynamic content like WordPress database query results, comments, and login status is cached, reducing database access frequency, improving data retrieval speed, and optimizing overall performance.
• Persistent caching strategy: Configure Redis to retain cache validity and expiration policies, ensuring that caching improves performance without expiring too quickly.
Image and media optimization
• Image Lazy Loading (deferred loading): Use plugins (such as WP Rocket or LazyLoad) to enable lazy loading, prioritizing the loading of content in the user's visible area, while other images are only loaded when they enter the visitor's visible area, reducing initial loading time (this feature has been enabled by default since WordPress version 5.5).
• Image optimization: Compress images through plugins (such as ShortPixel, Smush) or manually to reduce image file size and improve loading speed.
• WebP format: Use WebP format instead of traditional JPEG/PNG formats to provide smaller file sizes.
Database optimization
• Regularly optimize 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 times.
• Reduce unnecessary queries: Streamline WordPress queries to avoid high-frequency database access caused by plugins or themes.
Streamline plugins and themes
• Disable unnecessary plugins to reduce their impact 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 theme code clean.
CDN-level optimization options (taking Cloudflare as an example)
Cache rules
• Static resource caching: By configuring cache rules on a CDN (such as Cloudflare), static resources of the WordPress site (such as CSS, JS, images, etc.) are cached to CDN nodes. This reduces origin requests and speeds up the loading of static resources, thereby improving overall access speed.
• Full Page Caching: Cache WordPress pages in full via CDN, caching the entire page content (except for some uncacheable content) to CDN nodes, reducing server load and significantly lowering response times. This is especially suitable for pages that do not change frequently, such as article pages, static pages, etc.
• Caching Strategies and Fine-grained Control: Set appropriate caching strategies based on the update frequency of the content. For static resources that rarely change (such as images, CSS files, JavaScript files, etc.), a longer cache expiration time can be set; for frequently changing content (such as pages with personalized user information, user dashboards, etc.), caching should be avoided or a shorter cache expiration time should be set to ensure timely updates and accuracy of the content. It is particularly important to note that dynamic content such as comments is generally not suitable for caching, as this content changes with user interaction and must be dynamically generated.
• Edge Cache: By utilizing the edge cache provided by CDNs, cache the data closest to the user's node to improve loading speed. Edge caching improves the stability and speed of website access by reducing the load and response time of the origin server. By setting TTL (Time to Live), 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. Through Workers, you can flexibly adjust caching strategies based on factors such as user 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 provide finer-grained cache control, 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, reducing requests to the origin server and improving page loading speed. APO is highly suitable for most WordPress websites, especially those requiring high concurrency handling.
These are the conventional methods for optimizing and accelerating WordPress. However, in the past few days, I learned about another optimization method: instant.page, which uses a ”prefetching” approach (thanks to the recommendation of my friend ”tony8077616”). This method ”improves" the speed at which visitors open pages when visiting a WordPress site from another level. After testing it, I found it quite effective, so I am writing this article specifically to document it.
instant.page and ”Preloading”
What is ”Preloading”?
In fact, instant.page (official website:https://instant.page/)”s ”prefetching” is similar to the ”lazy loading” mentioned in the previous section ”Image and Media Optimization", and both can be considered“tricking” user perceptionan ”illusion” to improve the user's ”perceived loading speed”: it utilizes the ”time between hover and click” to prefetch, allowing the page content to be displayed almost instantly when the user clicks, thereby ”tricking the brain” (the human brain perceives actions taking less than 100 milliseconds as instant), making users feel the page loads faster, though the actual network loading speed remains unchanged.
Generally, the time it takes for a normal person to click a link is about 300+ milliseconds:

So theoretically, the ”prefetching” method can save at least 300+ milliseconds.
Technical Principles
instant.pageis actually just an independent piece of JavaScript code. Its main function is to listen for user hover events and prefetch 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 optimizes based on universal web interaction behaviors (such as hovering). On touchscreen devices, this process corresponds to the period from when the user touches the link to when the finger leaves the screen. Its technical principles are as follows:
- Listening for Hover Events: When a user hovers over a link, instant.page captures this behavior.
- Prefetching the Target Page: instant.page uses fetch() requests to prefetch the resources of the target page corresponding to the hovered link (such as HTML, CSS, JavaScript, etc.) in advance.
- Preparing Content in Advance: These prefetched resources are cached by the browser or stored in memory so that when the user clicks the link, the page is displayed almost instantly.
The relationship between instant.page and conventional optimization methods
Instant.pageAlthough it is a tool for prefetching page resources based on user behavior, it is not an independent performance optimization method. Instead, it relies on the traditional WordPress optimization methods mentioned earlier. Only after completing these traditional optimizations can Instant.page truly leverage its advantages, as shown in the following examples:
Synergy between WordPress Local-level Optimization and Instant.page
Static Page Caching and Browser Caching
• Instant.page's Dependency: When a user is browsing a page, Instant.page loads the static HTML file of the target link into the browser via prefetching. If static page caching is enabled (such as the functionality provided by WP Super Cache), Instant.page can directly load the cached static page instead of requesting a dynamically generated page, thereby significantly reducing server load and response times.
• Enhanced Effect: When browser caching is properly configured, Instant.page's prefetch requests will retrieve static resources like CSS and JS from the user's browser cache, rather than loading them from the server or CDN. This further accelerates page loading speed.
Redis Database Caching
• Instant.page's Dependency: Instant.page cannot directly optimize WordPress's dynamic queries, but if Redis has already cached the database query results, Instant.page's prefetch requests will trigger a fast response from Redis 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, preventing Instant.page's prefetching from causing database performance bottlenecks.
Image and Media Optimization
• Instant.page's Dependency: Instant.page's prefetching will trigger the loading of image resources. If lazy loading is enabled and optimized image formats (such as WebP) are used, the prefetched image resources will be smaller and faster.
• Enhanced Effect: By compressing images with plugins like ShortPixel or Smush, Instant.page's prefetch requests will consume less bandwidth and improve loading speed.
Synergy between CDN-level Optimization and Instant.page
CDN is an important tool for improving WordPress website performance. Its caching capabilities and edge computing support can significantly reduce origin pull pressure and accelerate page loading. Instant.page's prefetching feature can fully leverage the advantages of CDN, reading directly from CDN nodes when resources are already cached, further improving access speed.
Static resource caching
• Instant.page's Dependency: Through CDNs like Cloudflare, static resources (such as CSS, JS, images, etc.) are cached to the CDN nodes closest to the user. Instant.page's prefetch requests will prioritize retrieving resources from these nodes, reducing latency.
• Enhanced Effect: By properly setting caching strategies for static resources (such as long-term caching for rarely changing resources), Instant.page's prefetching can respond quickly, significantly reducing server load and network latency.
Full Page Caching
• Instant.page's Dependency: The full-page caching feature of CDNs (such as Cloudflare's APO) caches the entire page to edge nodes. In this case, Instant.page's prefetch requests do not require the server to generate page content, but instead directly load the cached HTML page.
• Enhanced Effect: For article pages or other content with low update frequency, full-page caching can work in tandem with Instant.page to achieve near-instant loading speeds.
Edge Caching and Edge Computing
• Instant.page's Dependency: Through Edge Cache, CDNs can cache the content recently accessed by users to nodes close to them. Instant.page's prefetching will load resources directly from edge nodes without needing to request the origin server.
• Enhanced Effect: By utilizing 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 feature can trigger these targeted optimizations.
Cloudflare Workers and Custom Optimization
• Instant.page's Dependency: Cloudflare Workers allow running custom logic on edge nodes. For example, dynamically generating different versions of page cache or handling special request conditions, Instant.page's preloading can directly cooperate with these custom caching logics.
• 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's Dependency: Cloudflare's APO is specifically optimized for WordPress, reducing server load by automatically caching pages and static resources. Instant.page's preloading integrates perfectly with APO, enabling direct loading of optimized content.
• Enhanced Effect: Especially in high-concurrency scenarios, APO provides stable cache response capabilities, ensuring that Instant.page's preloading does not fail due to server pressure or dynamic generation bottlenecks.
Refinement of Dynamic Content Caching
• Instant.page's Dependency: For dynamic content (such as comments, user dashboards, etc.), refining the caching strategy is crucial. For example, using Workers or other tools to dynamically generate non-cacheable parts of the content, Instant.page's preloading requests can trigger precisely controlled dynamic loading logic.
• Enhanced Effect: This optimization can balance the real-time nature of dynamic content with the loading speed of static content, making Instant.page's preloading compatible with complex scenarios.
Overall, CDN caching and optimization features provide solid foundational support for Instant.page: by properly configuring static resource caching, full-page caching, edge caching, and leveraging advanced features like 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, truly delivering an “instant click” user experience.
Deploying instant.page
The previous explanation of the principles was quite wordy, but the actual deployment of instant.page is very simple, because it is essentially just a piece of JS code, and there are multiple ways to deploy this code.
Deploying on WordPress
Using plugins
If deploying on WordPress, the easiest way is to use a plugin; you only need to directly install the instant.page plugin:

Just activate the plugin after installation, no extra settings are required:

Directly referencing the official script URL
You only need to insert the following code:
<script src="//instant.page/5.2.0" type="module" integrity="sha384-jnZyxPjiipYXnSU0ygqeac2q7CVYMbh84q0uHVRRxEtvFPiQYbXWUorga2aqZJ0z"></script>
into the WordPress footer.php file's</body>before (regular static HTML pages can be directly inserted before</body>).
Note: This method requires the client's browser to be able to loadhttps://instant.page/5.2.0this officially provided script URL normally.
Loading local JS scripts
This method requires placing the ”instantpage.js” script into the local WordPress path first, preferably in a subdirectory of wp-content, for example:
wp-content/js/instantpage.js
Then, just like before, in the footer.php file's/<body>before, insert the following code:
<script src="/wp-content/js/instantpage.js" type="module"></script>
Regarding the instantpage.js file, you can visit the instant.page homepage on GitHub (instant.page GitHub homepage) to view the latest version of the script, or obtain it directly from the address provided on the official website (https://instant.page/5.2.0):

However, the version on GitHub is newer; if you want to use it, try to use the version on GitHub. For friends who find it inconvenient to access GitHub, you can also download it from my ”Blog File Sharing Dedicated Link” (https://fileshare.tangwudi.com/s/file, sharing password: blog.tangwudi.com), as shown below:

Advanced version: Cloudflare Worker-based method
This method not only allows you to avoid installing plugins in your WordPress-built website (or directly introducing the instant.page script in the footer.php file), but also more efficiently utilizes 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 applicable. For specific steps to create a worker, please refer to the article:Home Data Center Series Cloudflare Tutorial (7): Introduction to CF Worker Functions and Practical Operation, Verification, and Related Technical Principles of Implementing ”Beggar's Version of APO for WordPress” Based on Worker to Accelerate Website Access。
The content of the worker script is 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);
}
To verify if the worker method is successful, you can use the browser's developer tools to view the site's HTML page source code and confirm whether<script src="https://instant.page/5.2.0"...> has been correctly injected into the end of the <body> tag. If so, the configuration is successful.
Note 1: Keep the double slashes in //instant.page to support protocol-relative loading, thereby automatically adapting to http or https.
Note 2: If you need to use other versions in the future, simply update the version number and the corresponding integrity value.
Note 3: Since Cloudflare Workers have a lower priority in the traffic sequence, they only take effect when other functional modules have not processed or intercepted the request. Therefore, to ensure that the Worker's script can run normally and achieve the expected effect, please properly configure higher-priority functional modules, such as ”Page Rules”, ”Cache Rules”, orWAFetc. For specific details about the ”traffic sequence”, please refer to the article:Home Data Center Series: Cloudflare Tutorial (Part 2) - Brief Introduction to the Functions of Technical Nodes in CF's Overall Solution Traffic Sequence。
Note 4: Using Cloudflare Workers may involve additional costs (the free plan has a limit of 100,000 requests per day, after which the default behavior is to deny access, though it can also be changed to direct origin fallback after exceeding the limit~). Please evaluate based on the actual traffic rate of your website.
Verifying the ”preloading” effect of instant.page
Verifying whether instant.page's ”preloading” is working is very easy; you only need to use the browser's developer tools.
First, find a page. For example, I will use my blog's ”AI Learning Map”:

Treat the link in the red box in the image above as the test link, and then open the browser's developer tools (I am using Chrome):

Then, hover the mouse over the links of the 6 articles one by one from top to bottom, and observe the network logs recorded in the developer tools on the right:

You can see that the ”preloading” effect is working.
Besides ”deception”, is there also ”sincerity”?
Preloading can also shorten the overall page loading time
Although ”preloading” can make visitors think the access speed has improved by ”tricking” their brains, is it really completely unhelpful in shortening the actual loading time of the entire page?
In fact, Instant.page can actually shorten webpage loading times in certain situations, rather than just ”tricking” the visitor's brain. Although its core mechanism of ”preloading” aims to improve user experience and give a ”faster” feeling, this does not mean it has zero impact on actual loading times in all scenarios. Here are several situations where it can help shorten loading times:
Latency Reduction
Instant.page's preloading mechanism actively loads the target page's resources when the user hovers the mouse over a link. Because the request to load resources is sent in advance, it can significantly reduce the time users wait for the server to respond after clicking the link.
• Applicable Scenarios: Websites with slow server responses in high-latency network environments.
• Actual effect: When a user clicks a link, the resources of the target page may have already been fully or partially loaded, thereby reducing the time required for subsequent loading.
Make full use of idle bandwidth time
During the short period before a user clicks a link (such as when the mouse hovers or a touchscreen user pauses briefly), the network is usually idle. Instant.page utilizes this idle time to send preloading requests.
• Applicable Scenarios: Network environments with sufficient bandwidth.
• Actual effect: These resources are already loaded or cached before the user clicks the link, eliminating the need for repeated requests when the page loads, which actually accelerates page loading.
Integration with caching mechanisms
Instant.page's preloading mechanism can better cooperate with caching strategies (such as CDN and browser caching) to load resources in advance, thereby improving the page loading experience.
• CDN caching: When the resources of the target page have already been cached on CDN nodes, Instant.page's preloading requests will also fetch resources directly from the CDN, thereby avoiding unnecessary origin-pull requests. Although this is not essentially different from requesting resources upon a direct click, preloading triggers the request in advance, allowing resource loading to complete earlier.
• Browser caching: Instant.page's preloading requests store the target resources in the browser cache. When the user officially visits the page, the browser can directly call the cached resources, avoiding re-initiating requests and thus reducing loading time.
• Applicable Scenarios: The website has enabled effective caching strategies (such as long-term caching rules for static resources); resources are distributed via CDN, and there is low latency between the user's network and the CDN nodes.
• Actual effect: Instant.page completes the loading or partial loading of resources in advance, shortening the loading time after the user clicks; the browser caching mechanism further reduces repeated requests, optimizing page loading efficiency.
Fast pre-generation of dynamic content
For dynamic content (such as personalized pages), if the website cooperates with server-side technologies (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: Websites where dynamic page loading requires content generation.
• Actual effect: Before the user officially requests the page, the dynamic content is already generated and can respond quickly.
Reducing Time to First Byte (TTFB)
Through Instant.page's advance requests, the browser and server can complete TCP connection establishment, SSL handshakes, and initial resource acquisition ahead of time, thereby shortening the page's TTFB.
• Applicable Scenarios: Websites with longer TTFB.
• Actual effect: The reduction in Time to First Byte directly reduces the total loading time.
Improving above-the-fold loading speed
Instant.page focuses on preloading key resources of the target page (such as HTML files), which allows the above-the-fold content to render faster when the user enters a new page.
• Applicable Scenarios: Websites with high user experience requirements for above-the-fold rendering time.
• Actual effect: Even if non-critical resources still need to load, the user-perceived above-the-fold rendering speed is faster, and the actual page loading time is shortened as a result.
In summary, although Instant.page's mechanism improves perceived speed by ”tricking” the visitor's brain, it is not entirely incapable of shortening actual loading times. In specific scenarios, it has a real impact on webpage loading times in the following ways:
• Initiating resource requests in advance to reduce latency.
• Utilizing idle bandwidth to improve resource loading efficiency.
• Cooperating with caching strategies or dynamic generation mechanisms to optimize loading performance.
However, the realization of these effects highly depends on the website's basic optimization (such as caching strategies, CDN deployment, etc.). If the website optimization is inadequate (for example, no CDN or caching strategy), the actual help of Instant.page will be greatly compromised, remaining more at the level of “perceived speed improvement.”
How to verify the above conclusion?
Originally, I wanted to use Google's website speed test ”PageSpeed Insights” to verify the conclusion drawn in the previous section: that instant.page can shorten actual loading times in specific scenarios. However, the key problem is that even if I normally use ”PageSpeed Insights” to test twice in a row, the score results might differ significantly, such as in this test result:
First time:

Second time:

Therefore, it is impossible to see the effect directly from the scores. It seems we need to focus on the numerical changes of these 5 key parameters: First Contentful Paint (FCP), Largest Contentful Paint (LCP), Total Blocking Time, Cumulative Layout Shift (CLS), and Speed Index.
However, theoretically speaking, instant.page's ”preloading” is not effective for every parameter, so we first need to theoretically analyze the impact of preloading on each parameter:
First Contentful Paint (FCP)
• Definition: The time when the page first renders any visible content.
• instant.page 's Impact: Significant optimization. Preloading fetches key resources (such as HTML, CSS) in advance, allowing the page to start rendering content faster.
Largest Contentful Paint (LCP)
• Definition: The rendering time of the largest visible content on the page.
• instant.page 's Impact: Significant optimization. Key resources (such as images or main text blocks) are loaded in advance, reducing waiting time and thus shortening LCP.
Total Blocking Time (TBT)
• Definition: The total amount of time the main thread is blocked by long tasks.
• instant.page 's Impact: No significant impact. The preloading mechanism does not reduce the parsing and execution time of JavaScript, but loading resources in advance may indirectly reduce some blocking related to resource loading.
Cumulative Layout Shift (CLS)
• Definition: The stability of the layout during the page loading process.
• instant.page 's Impact: No significant impact. Preloading does not directly intervene in layout shifts, but if resources are loaded in advance (such as fonts or images), it may indirectly reduce layout jitter caused by resource loading delays.
Speed Index
• Definition: The speed at which visible content is displayed during the page loading process.
• instant.page 's Impact: Significant optimization. Preloading resources allows the page to display visible content faster, thereby improving the Speed Index.
| Performance Metrics | instant.page Optimization Effects of |
Impact Analysis |
|---|---|---|
| First Contentful Paint (FCP) | Significant Optimization | Preload resources to speed up the first contentful paint time. |
| Largest Contentful Paint (LCP) | Significant Optimization | Preload critical resources to render the largest content block faster. |
| Total Blocking Time (TBT) | No Significant Impact | Does not interfere with main thread tasks, only indirectly reducing blocking caused by some resource loading. |
| Cumulative Layout Shift (CLS) | No Significant Impact | Weak relationship with layout shifts, but indirectly reduces layout instability caused by resource delays. |
| Speed Index | Significant Optimization | Resource preloading improves the coherence and speed of page display. |
Notes:
1. FCP and LCP are the metrics most affected by instant.page, suitable for scenarios that require speeding up above-the-fold and main content loading.
If you need to optimize TBT 和 CLS, you need to combine other methods (such as optimizing JavaScript and avoiding layout shifts).
Actual verification
Note: To do this experiment, I have to first disable the instant.page plugin, then clear all cache on Cloudflare, and then run ”PageSpeed Insights” once; then enable instant.page, clear all cache on Cloudflare again, and run ”PageSpeed Insights” once more. For the sake of science, I sacrificed so much~.
Results of disabling instant.page:

Results of enabling instant.page:

Well, it feels like the differences are all within a reasonable margin of error. It seems the results of this test cannot verify the conclusion of the previous section. The experiment failed. I feel it's because after using Cloudflare's CDN, many extra factors were introduced during the testing process. It would probably be more straightforward without a CDN, but I really don't have the energy to mess around with it anymore~.
“Special handling for ”Log out” and ”Exit" buttons
After using instant.page to implement the preloading function, there is an issue: when the mouse hovers over the ”Log out” or ”Exit” buttons, they are executed directly. At this point, the logged-in user might not even realize the issue, and executing some actions that require login will result in errors.
So, how can we optimize this issue in WordPress? Here are a few ideas for optimization methods for your reference:
Exclude preloading of sensitive links
Method: Use the data-no-instant attribute
In WordPress, “Log out” and other sensitive links are usually generated by themes or plugins. You can add data-no-instant in the following ways:
a. Modify theme template files
Find the template code that generates these links (such as wp_nav_menu() or other menu-generating code) and manually add data-no-instant.
Example code:
<?phpwp_nav_menu(array("theme_location' => 'primary','items_wrap' => '<ul id="%1s" class="%2, s">%3,s', 'walker' => new class extends Walker_Nav_Menu {,public function start_el(&
output,item,depth = 0,args = null,
b. Dynamically add via WordPress hooks
If you use the default menu generation function, you can dynamically modify link attributes via the wp_nav_menu_items or wp_get_nav_menu_items hooks:
add_filter('wp_nav_menu_items', function(items) {'return preg_replace("/href=['\'](.*logout.*)["\']/', 'href=";
Dynamically block using JavaScript
In WordPress, you can write this logic into your theme's custom JavaScript file or add it via a plugin. For example:
Method: Add script via 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 example content:
document.querySelectorAll('a[href*="logout"]').forEach(link => {
link.setAttribute('data-no-instant', '');
});
Use JavaScript to validate actions
In WordPress, you can add a confirmation popup or extra validation for sensitive links (such as “Log out”). This is suitable for buttons or links generated by plugins or themes.
Method: Add confirmation popup
In the template file, add the onclick attribute to specific links:
<a href="/en/</?php echo wp_logout_url(); ?>" onclick="return confirm('确定要注销吗?');">Log out</a>
Or dynamically add via a global script:
document.querySelectorAll('a[href*="logout"]').forEach(link => {
link.addEventListener('click', function(e) {
if (!confirm('确定要注销吗?')) {
e.preventDefault();
}
});
});
Backend Logic Optimization
WordPress provides a rich set of filters and actions that can intercept requests on the backend. For example:
Method: Determine Preload Requests
You can detect preloading request headers (such as X-Instant-Page) via PHP and avoid executing sensitive operations.
add_action('wp_logout', function() {
if (!empty($_SERVER['HTTP_X_INSTANT_PAGE'])) {
wp_die('此操作无法通过预加载完成,请重新点击注销按钮。');
}
});
Configure Instant.page Options
In WordPress, you can control the behavior of Instant.page with finer granularity in the following ways:
Method: Configure Loading Parameters
Add the Instant.page script to your theme or plugin and set the parameters:
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}');
});
The above operations can effectively prevent triggering preloads during brief hovers. You can choose the optimization method that best suits your actual situation.
Note: Thanks to friend ”Qiufeng yu Weishui” for the reminder in the comment section.
Afterword
Originally, I just wanted to write a low-effort post to get through the week, but I didn't expect to end up tinkering around again. However, from the perspective of WordPress optimization, I think Instant.page is well worth the effort. After all, it optimizes the WordPress user experience from another level, which is quite interesting. Crucially, deployment is simple—just a few lines of code or a plugin. I recommend all friends using WordPress to give it a try.
By the way, if you want to implement this yourself, please make sure to exclude links like [Log Out] and [Exit]. Otherwise, if the mouse accidentally hovers over the [Log Out] button, the WP login status will be gone. I once had a very painful troubleshooting process because of this, searching all over only to find out it was the fault of preloading.
Thanks, this reminder is very important. I will add it to the article later. My blog currently has registration disabled, so I won't encounter this issue, but other bloggers who allow registration definitely need to pay attention to this.