文章目录
-
- 在当今电子商务竞争激烈的环境中,网站加载速度直接影响着用户体验、转化率和搜索引擎排名。根据Google的研究,页面加载时间每增加1秒,移动端转化率就会下降20%。对于使用WooCommerce的WordPress电商网站来说,产品页通常是用户做出购买决策的关键页面,其加载速度尤为重要。 WooCommerce产品页通常包含大量动态内容:产品图片库、变体选择器、相关产品推荐、用户评价等,这些元素都可能成为性能瓶颈。本文将深入探讨三个关键技术,帮助您显著提升WooCommerce产品页的加载速度,从而改善用户体验并提高销售转化率。
-
- 图像通常是产品页中最大的资源,实现懒加载可以显著减少初始页面加载时间。 /** * 为WooCommerce产品图片添加懒加载功能 * 将以下代码添加到主题的functions.php文件中 */ function add_lazy_loading_to_product_images() { // 检查是否为产品页面 if (is_product()) { // 移除WooCommerce默认的产品图片输出 remove_action('woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20); // 添加自定义的懒加载产品图片 add_action('woocommerce_before_single_product_summary', 'custom_lazy_load_product_images', 20); } } add_action('wp', 'add_lazy_loading_to_product_images'); /** * 自定义懒加载产品图片函数 */ function custom_lazy_load_product_images() { global $product; // 获取产品图片ID $product_id = $product->get_id(); $main_image_id = $product->get_image_id(); $gallery_image_ids = $product->get_gallery_image_ids(); // 输出主图片 if ($main_image_id) { echo '<div class="woocommerce-product-gallery__image single-product-main-image">'; echo wp_get_attachment_image( $main_image_id, 'woocommerce_single', false, array( 'class' => 'wp-post-image lazy-load', 'data-src' => wp_get_attachment_image_url($main_image_id, 'woocommerce_single'), 'src' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', // 占位图 'alt' => get_post_meta($main_image_id, '_wp_attachment_image_alt', true) ?: get_the_title($product_id) ) ); echo '</div>'; } // 输出图库图片 if ($gallery_image_ids) { echo '<div class="product-gallery-thumbnails">'; foreach ($gallery_image_ids as $gallery_image_id) { echo '<div class="gallery-thumbnail">'; echo wp_get_attachment_image( $gallery_image_id, 'woocommerce_gallery_thumbnail', false, array( 'class' => 'lazy-load', 'data-src' => wp_get_attachment_image_url($gallery_image_id, 'woocommerce_gallery_thumbnail'), 'src' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'alt' => get_post_meta($gallery_image_id, '_wp_attachment_image_alt', true) ?: get_the_title($product_id) ) ); echo '</div>'; } echo '</div>'; } // 添加懒加载JavaScript add_lazy_load_script(); } /** * 添加懒加载JavaScript代码 */ function add_lazy_load_script() { ?> <script> document.addEventListener("DOMContentLoaded", function() { // 懒加载实现 const lazyImages = document.querySelectorAll('img.lazy-load'); // 创建Intersection Observer实例 const imageObserver = new IntersectionObserver(function(entries, observer) { entries.forEach(function(entry) { if (entry.isIntersecting) { const img = entry.target; img.src = img.dataset.src; img.classList.remove('lazy-load'); imageObserver.unobserve(img); } }); }); // 观察所有懒加载图片 lazyImages.forEach(function(img) { imageObserver.observe(img); }); // 备用方案:如果浏览器不支持Intersection Observer if (!('IntersectionObserver' in window)) { const lazyLoadFallback = function() { lazyImages.forEach(function(img) { if (img.getBoundingClientRect().top < window.innerHeight && img.getBoundingClientRect().bottom > 0) { img.src = img.dataset.src; img.classList.remove('lazy-load'); } }); }; // 监听滚动事件 window.addEventListener('scroll', lazyLoadFallback); window.addEventListener('resize', lazyLoadFallback); lazyLoadFallback(); // 初始执行 } }); </script> <?php }
- 除了懒加载,正确的图像格式选择和压缩也至关重要: 使用WebP格式:WebP比JPEG和PNG有更好的压缩率,同时保持相同质量 实施响应式图像:根据设备屏幕尺寸提供不同大小的图像 使用图像压缩插件:如ShortPixel、Imagify或EWWW Image Optimizer
-
- WooCommerce产品页通常执行大量数据库查询,优化这些查询可以显著提升性能。 /** * 优化WooCommerce产品页数据库查询 * 减少不必要的查询并添加缓存 */ // 缓存产品变体数据 function cache_product_variations($product_id) { // 检查是否为变体产品 $product = wc_get_product($product_id); if (!$product->is_type('variable')) { return false; } // 尝试从缓存获取变体数据 $cache_key = 'product_variations_' . $product_id; $cached_variations = wp_cache_get($cache_key, 'woocommerce'); if (false === $cached_variations) { // 缓存中没有数据,从数据库获取 $variations = $product->get_available_variations(); // 优化变体数据,只保留必要信息 $optimized_variations = array(); foreach ($variations as $variation) { $optimized_variations[] = array( 'variation_id' => $variation['variation_id'], 'attributes' => $variation['attributes'], 'price_html' => $variation['price_html'], 'image' => $variation['image'], 'is_in_stock' => $variation['is_in_stock'] ); } // 将数据存入缓存,有效期1小时 wp_cache_set($cache_key, $optimized_variations, 'woocommerce', HOUR_IN_SECONDS); return $optimized_variations; } return $cached_variations; } // 在产品页使用缓存的变体数据 function display_optimized_product_variations() { global $product; if ($product->is_type('variable')) { $variations = cache_product_variations($product->get_id()); if ($variations) { // 使用缓存的数据显示变体选择器 echo '<div class="variations_form">'; // ... 变体选择器HTML代码 echo '</div>'; } } } add_action('woocommerce_before_add_to_cart_form', 'display_optimized_product_variations'); // 清除产品变体缓存 function clear_product_variation_cache($product_id) { $cache_key = 'product_variations_' . $product_id; wp_cache_delete($cache_key, 'woocommerce'); } add_action('woocommerce_update_product', 'clear_product_variation_cache'); add_action('woocommerce_delete_product', 'clear_product_variation_cache');
- 对于高流量网站,实施对象缓存可以显著减少数据库查询: 使用Redis或Memcached:安装并配置对象缓存扩展 配置WooCommerce支持对象缓存:在wp-config.php中添加相应配置 使用缓存插件:如W3 Total Cache或WP Rocket
- 确保WooCommerce相关数据库表有适当的索引: -- 为WooCommerce订单项表添加索引 ALTER TABLE wp_woocommerce_order_items ADD INDEX order_id (order_id); -- 为产品元数据表添加索引 ALTER TABLE wp_postmeta ADD INDEX post_id_meta_key (post_id, meta_key(50)); -- 为产品变体属性表添加索引 ALTER TABLE wp_woocommerce_attribute_taxonomies ADD INDEX attribute_name (attribute_name(20));
-
- 产品页中的许多JavaScript文件可以延迟加载,直到用户交互时再执行。 /** * 优化WooCommerce产品页JavaScript加载 * 延迟非关键脚本,异步加载必要脚本 */ // 延迟加载WooCommerce变体脚本 function defer_woocommerce_variation_script($tag, $handle, $src) { // 延迟的脚本列表 $scripts_to_defer = array( 'wc-add-to-cart-variation', 'zoom', 'flexslider', 'photoswipe-ui-default' ); // 异步加载的脚本列表 $scripts_to_async = array( 'wc-single-product', 'wc-add-to-cart' ); if (in_array($handle, $scripts_to_defer)) { return str_replace(' src', ' defer src', $tag); } if (in_array($handle, $scripts_to_async)) { return str_replace(' src', ' async src', $tag); } return $tag; } add_filter('script_loader_tag', 'defer_woocommerce_variation_script', 10, 3); // 条件加载JavaScript function conditionally_load_product_scripts() { // 只在产品页面加载特定脚本 if (is_product()) { // 移除不必要的脚本 wp_dequeue_script('some-unnecessary-script'); // 延迟加载评价相关脚本 add_filter('script_loader_tag', function($tag, $handle) { if ($handle === 'comment-reply') { return str_replace(' src', ' defer src', $tag); } return $tag; }, 10, 2); } } add_action('wp_enqueue_scripts', 'conditionally_load_product_scripts', 100);
- /** * 提取并内联关键CSS,延迟加载非关键CSS */ // 提取产品页关键CSS function get_product_critical_css() { // 这里应该是从CSS文件中提取的关键CSS代码 // 实际应用中可以使用自动化工具提取 return ' .woocommerce-product-gallery { opacity: 1 !important; } .product_title { font-size: 24px; margin-bottom: 15px; } .price { color: #77a464; font-size: 22px; } .woocommerce-product-details__short-description { margin-bottom: 20px; } .single_add_to_cart_button { background: #a46497; color: white; padding: 10px 20px; border: none; } '; } // 内联关键CSS并延迟加载主样式表 function optimize_product_page_css() { if (is_product()) { // 获取关键CSS $critical_css = get_product_critical_css(); // 内联关键CSS echo '<style id="critical-css">' . $critical_css . '</style>'; // 延迟加载主CSS文件 add_filter('style_loader_tag', function($html, $handle) { if ($handle === 'woocommerce-general' || $handle === 'woocommerce-layout') { return str_replace("media='all'", "media='print' onload="this.media='all'"", $html); } return $html; }, 10, 2); } } add_action('wp_head', 'optimize_product_page_css', 1);
- 对于现代JavaScript,可以使用代码分割技术: // 动态加载产品变体选择器脚本 if (document.querySelector('.variations_form')) { import('./product-variation-handler.js') .then(module => { module.initVariationHandler(); }) .catch(error => { console.error('动态加载变体处理器失败:', error); }); } // 动态加载产品图库脚本 if (document.querySelector('.woocommerce-product-gallery')) { import('./product-gallery.js') .then(module => { module.initProductGallery(); }) .catch(error => { console.error('动态加载产品图库失败:', error); }); }
-
- 图像优化检查: [ ] 启用图像懒加载 [ ] 转换图像为WebP格式 [ ] 实施响应式图像 [ ] 压缩所有产品图片 数据库与缓存优化: [ ] 实施数据库查询缓存 [ ] 配置对象缓存(Redis/Memcached) [ ] 优化数据库索引 [ ] 启用页面缓存 代码优化: [ ] 延迟非关键JavaScript [ ] 内联关键CSS [ ] 最小化CSS和JavaScript文件 [ ] 移除未使用的代码
- 实施优化后,使用以下工具测试性能改进: Google PageSpeed Insights:全面的性能分析和建议 GTmetrix:详细的加载时间分析和瀑布图 WebPageTest:多地点测试和视频录制功能 Pingdom Tools:简单的速度测试和性能评分
- 性能优化不是一次性的任务,需要持续监控: 设置定期性能检查(每周或每月) 监控关键指标:首次内容绘制(FCP)、最大内容绘制(LCP)、首次输入延迟(FID) 使用监控工具如New Relic或Google Analytics Site Speed报告 定期更新WooCommerce和主题,确保兼容性和性能改进
- 通过实施上述三个关键技术——优化图像与媒体资源、数据库查询优化与缓存策略、JavaScript与CSS优化,您可以显著提升WooCommerce产品页的加载速度。这些优化不仅改善用户体验,还能直接提高转化率和搜索引擎排名。 记住,性能优化是一个持续的过程。随着WooCommerce的更新、新功能的添加和产品数量的增加,定期重新评估和优化您的网站性能至关重要。从今天开始实施这些技术,您将很快看到网站性能的显著提升和业务指标的积极变化。 最佳实践提示:在实施任何重大更改之前,始终在暂存环境中测试,并确保有完整的网站备份。性能优化应该是一个渐进的过程,一次实施一个更改,测试其效果,然后再进行下一个优化。
-
-
- 服务器配置直接影响WooCommerce产品页的加载性能。以下是最佳实践配置: # Nginx服务器配置优化示例 # /etc/nginx/nginx.conf 或站点配置文件 http { # 基础优化 sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # 启用Gzip压缩 gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xml+rss application/atom+xml image/svg+xml; # 静态资源缓存 location ~* .(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ { expires 1y; add_header Cache-Control "public, immutable"; add_header Vary Accept-Encoding; # 启用Brotli压缩(如果可用) brotli on; brotli_types text/plain text/css application/javascript application/json image/svg+xml; brotli_comp_level 6; } # WooCommerce特定规则 location /wp-content/uploads/woocommerce_uploads/ { expires 1y; add_header Cache-Control "public"; } # PHP-FPM优化 location ~ .php$ { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; # PHP-FPM性能优化 fastcgi_buffer_size 128k; fastcgi_buffers 256 16k; fastcgi_busy_buffers_size 256k; fastcgi_temp_file_write_size 256k; } }
- ; php.ini 配置优化 ; 适用于WooCommerce的PHP设置 [PHP] ; 内存限制 memory_limit = 256M ; 执行时间 max_execution_time = 300 max_input_time = 300 ; 输出缓冲 output_buffering = 4096 implicit_flush = Off ; 会话设置 session.gc_maxlifetime = 1440 session.cookie_lifetime = 0 ; OPcache优化(PHP 7.0+) [opcache] opcache.enable=1 opcache.memory_consumption=256 opcache.interned_strings_buffer=16 opcache.max_accelerated_files=10000 opcache.revalidate_freq=2 opcache.fast_shutdown=1 opcache.enable_cli=1 opcache.save_comments=1 ; 实时优化配置 opcache.revalidate_freq=0 opcache.validate_timestamps=0 ; 生产环境设为0,开发环境设为1
- # Apache HTTP/2配置示例 # .htaccess 或虚拟主机配置 <IfModule mod_http2.c> # 启用HTTP/2 Protocols h2 h2c http/1.1 # HTTP/2推送配置 H2Push on H2PushPriority * after # 推送关键资源 <FilesMatch ".(css|js)$"> H2PushResource on </FilesMatch> # 连接设置 H2MaxSessionStreams 100 H2WindowSize 65535 H2StreamMaxMemSize 128000 </IfModule> # 启用Brotli压缩 <IfModule mod_brotli.c> AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml application/rss+xml image/svg+xml </IfModule> # 资源提示 <IfModule mod_headers.c> # 预连接关键域名 Header add Link "</wp-content/themes/your-theme/style.css>; rel=preload; as=style" Header add Link "</wp-includes/js/jquery/jquery.min.js>; rel=preload; as=script" # DNS预获取 Header add Link "<//fonts.googleapis.com>; rel=dns-prefetch" Header add Link "<//ajax.googleapis.com>; rel=dns-prefetch" </IfModule>
-
- /** * WooCommerce CDN集成配置 * 将静态资源重定向到CDN */ class WooCommerce_CDN_Integration { private $cdn_domain = 'https://cdn.yourdomain.com'; private $excluded_files = array('admin-ajax.php', 'wc-api'); public function __construct() { // 初始化CDN集成 add_action('init', array($this, 'setup_cdn')); } public function setup_cdn() { // 只在前端启用CDN if (!is_admin()) { // 重写静态资源URL add_filter('wp_get_attachment_url', array($this, 'rewrite_attachment_url'), 10, 2); add_filter('stylesheet_directory_uri', array($this, 'rewrite_theme_url')); add_filter('template_directory_uri', array($this, 'rewrite_theme_url')); add_filter('plugins_url', array($this, 'rewrite_plugins_url')); // 处理WooCommerce特定资源 add_filter('woocommerce_product_get_image_id', array($this, 'optimize_product_images')); } } public function rewrite_attachment_url($url, $post_id) { // 只处理图片和文档 $file_type = get_post_mime_type($post_id); $allowed_types = array('image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'); if (in_array($file_type, $allowed_types)) { $parsed_url = parse_url($url); $path = $parsed_url['path']; // 排除特定文件 foreach ($this->excluded_files as $excluded) { if (strpos($path, $excluded) !== false) { return $url; } } // 构建CDN URL return $this->cdn_domain . $path; } return $url; } public function rewrite_theme_url($url) { // 重写主题资源URL $parsed_url = parse_url($url); $path = $parsed_url['path']; // 只处理CSS、JS和字体文件 if (preg_match('/.(css|js|woff|woff2|ttf|eot|svg)$/', $path)) { return $this->cdn_domain . $path; } return $url; } public function rewrite_plugins_url($url) { // 重写插件资源URL $parsed_url = parse_url($url); $path = $parsed_url['path']; // 检查是否为WooCommerce资源 if (strpos($path, '/woocommerce/') !== false) { // 只处理特定文件类型 if (preg_match('/.(css|js|png|jpg|gif|svg)$/', $path)) { return $this->cdn_domain . $path; } } return $url; } public function optimize_product_images($image_id) { // 为产品图片添加CDN参数 if ($image_id) { add_filter('wp_get_attachment_image_src', function($image, $id) use ($image_id) { if ($id == $image_id && isset($image[0])) { // 添加自动优化参数(适用于支持图片处理的CDN) $image[0] = add_query_arg(array( 'width' => $image[1], 'height' => $image[2], 'fit' => 'cover', 'quality' => 85, 'format' => 'auto' // 自动选择最佳格式 ), $image[0]); } return $image; }, 10, 2); } return $image_id; } /** * 生成CDN预取头 */ public function add_cdn_prefetch_headers() { if (!is_admin()) { header("Link: <{$this->cdn_domain}>; rel=preconnect; crossorigin", false); header("Link: <{$this->cdn_domain}/wp-content/uploads/>; rel=prefetch", false); header("Link: <{$this->cdn_domain}/wp-content/themes/>; rel=prefetch", false); } } } // 初始化CDN集成 new WooCommerce_CDN_Integration();
- // 边缘计算示例:在CDN边缘处理产品变体计算 // 这个示例展示如何使用Cloudflare Workers处理变体价格计算 addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // 只处理产品变体API请求 const url = new URL(request.url) if (url.pathname.includes('/wc-api/variations/')) { return handleVariationRequest(request, url) } // 其他请求直接传递 return fetch(request) } async function handleVariationRequest(request, url) { // 从URL获取产品ID和属性 const productId = url.pathname.split('/').pop() const searchParams = new URLSearchParams(url.search) // 构建缓存键 const cacheKey = `variation_${productId}_${Array.from(searchParams.entries()).sort().toString()}` // 检查边缘缓存 const cache = caches.default let response = await cache.match(request) if (!response) { // 缓存未命中,从源站获取 response = await fetch(request.clone()) if (response.status === 200) { // 克隆响应以修改 const newResponse = new Response(response.body, response) // 添加边缘缓存头 newResponse.headers.set('Cache-Control', 'public, max-age=3600') newResponse.headers.set('CDN-Cache-Control', 'public, max-age=3600') newResponse.headers.set('Vary', 'Accept-Encoding, User-Agent') // 存储到边缘缓存 event.waitUntil(cache.put(request, newResponse.clone())) return newResponse } } return response } // 边缘计算:实时价格计算 async function calculateDynamicPrice(productData, variationAttributes) { // 从边缘KV存储获取价格规则 const pricingRules = await PRICING_KV.get('pricing_rules', 'json') // 应用价格规则 let basePrice = productData.price let finalPrice = basePrice // 检查批量折扣 if (pricingRules.bulk_discounts) { for (const rule of pricingRules.bulk_discounts) { if (variationAttributes.quantity >= rule.min_quantity) { finalPrice = basePrice * (1 - rule.discount_percent / 100) break } } } // 检查会员折扣 if (pricingRules.member_discounts && variationAttributes.is_member) { finalPrice *= (1 - pricingRules.member_discounts.percent / 100) } return { price: finalPrice.toFixed(2), original_price: basePrice.toFixed(2), discount: ((basePrice - finalPrice) / basePrice * 100).toFixed(1) } }
-
在当今电子商务竞争激烈的环境中,网站加载速度直接影响着用户体验、转化率和搜索引擎排名。根据Google的研究,页面加载时间每增加1秒,移动端转化率就会下降20%。对于使用WooCommerce的WordPress电商网站来说,产品页通常是用户做出购买决策的关键页面,其加载速度尤为重要。
WooCommerce产品页通常包含大量动态内容:产品图片库、变体选择器、相关产品推荐、用户评价等,这些元素都可能成为性能瓶颈。本文将深入探讨三个关键技术,帮助您显著提升WooCommerce产品页的加载速度,从而改善用户体验并提高销售转化率。
图像通常是产品页中最大的资源,实现懒加载可以显著减少初始页面加载时间。
/**
* 为WooCommerce产品图片添加懒加载功能
* 将以下代码添加到主题的functions.php文件中
*/
function add_lazy_loading_to_product_images() {
// 检查是否为产品页面
if (is_product()) {
// 移除WooCommerce默认的产品图片输出
remove_action('woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20);
// 添加自定义的懒加载产品图片
add_action('woocommerce_before_single_product_summary', 'custom_lazy_load_product_images', 20);
}
}
add_action('wp', 'add_lazy_loading_to_product_images');
/**
* 自定义懒加载产品图片函数
*/
function custom_lazy_load_product_images() {
global $product;
// 获取产品图片ID
$product_id = $product->get_id();
$main_image_id = $product->get_image_id();
$gallery_image_ids = $product->get_gallery_image_ids();
// 输出主图片
if ($main_image_id) {
echo '<div class="woocommerce-product-gallery__image single-product-main-image">';
echo wp_get_attachment_image(
$main_image_id,
'woocommerce_single',
false,
array(
'class' => 'wp-post-image lazy-load',
'data-src' => wp_get_attachment_image_url($main_image_id, 'woocommerce_single'),
'src' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', // 占位图
'alt' => get_post_meta($main_image_id, '_wp_attachment_image_alt', true) ?: get_the_title($product_id)
)
);
echo '</div>';
}
// 输出图库图片
if ($gallery_image_ids) {
echo '<div class="product-gallery-thumbnails">';
foreach ($gallery_image_ids as $gallery_image_id) {
echo '<div class="gallery-thumbnail">';
echo wp_get_attachment_image(
$gallery_image_id,
'woocommerce_gallery_thumbnail',
false,
array(
'class' => 'lazy-load',
'data-src' => wp_get_attachment_image_url($gallery_image_id, 'woocommerce_gallery_thumbnail'),
'src' => 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7',
'alt' => get_post_meta($gallery_image_id, '_wp_attachment_image_alt', true) ?: get_the_title($product_id)
)
);
echo '</div>';
}
echo '</div>';
}
// 添加懒加载JavaScript
add_lazy_load_script();
}
/**
* 添加懒加载JavaScript代码
*/
function add_lazy_load_script() {
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
// 懒加载实现
const lazyImages = document.querySelectorAll('img.lazy-load');
// 创建Intersection Observer实例
const imageObserver = new IntersectionObserver(function(entries, observer) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy-load');
imageObserver.unobserve(img);
}
});
});
// 观察所有懒加载图片
lazyImages.forEach(function(img) {
imageObserver.observe(img);
});
// 备用方案:如果浏览器不支持Intersection Observer
if (!('IntersectionObserver' in window)) {
const lazyLoadFallback = function() {
lazyImages.forEach(function(img) {
if (img.getBoundingClientRect().top < window.innerHeight && img.getBoundingClientRect().bottom > 0) {
img.src = img.dataset.src;
img.classList.remove('lazy-load');
}
});
};
// 监听滚动事件
window.addEventListener('scroll', lazyLoadFallback);
window.addEventListener('resize', lazyLoadFallback);
lazyLoadFallback(); // 初始执行
}
});
</script>
<?php
}
除了懒加载,正确的图像格式选择和压缩也至关重要:
- 使用WebP格式:WebP比JPEG和PNG有更好的压缩率,同时保持相同质量
- 实施响应式图像:根据设备屏幕尺寸提供不同大小的图像
- 使用图像压缩插件:如ShortPixel、Imagify或EWWW Image Optimizer
WooCommerce产品页通常执行大量数据库查询,优化这些查询可以显著提升性能。
/**
* 优化WooCommerce产品页数据库查询
* 减少不必要的查询并添加缓存
*/
// 缓存产品变体数据
function cache_product_variations($product_id) {
// 检查是否为变体产品
$product = wc_get_product($product_id);
if (!$product->is_type('variable')) {
return false;
}
// 尝试从缓存获取变体数据
$cache_key = 'product_variations_' . $product_id;
$cached_variations = wp_cache_get($cache_key, 'woocommerce');
if (false === $cached_variations) {
// 缓存中没有数据,从数据库获取
$variations = $product->get_available_variations();
// 优化变体数据,只保留必要信息
$optimized_variations = array();
foreach ($variations as $variation) {
$optimized_variations[] = array(
'variation_id' => $variation['variation_id'],
'attributes' => $variation['attributes'],
'price_html' => $variation['price_html'],
'image' => $variation['image'],
'is_in_stock' => $variation['is_in_stock']
);
}
// 将数据存入缓存,有效期1小时
wp_cache_set($cache_key, $optimized_variations, 'woocommerce', HOUR_IN_SECONDS);
return $optimized_variations;
}
return $cached_variations;
}
// 在产品页使用缓存的变体数据
function display_optimized_product_variations() {
global $product;
if ($product->is_type('variable')) {
$variations = cache_product_variations($product->get_id());
if ($variations) {
// 使用缓存的数据显示变体选择器
echo '<div class="variations_form">';
// ... 变体选择器HTML代码
echo '</div>';
}
}
}
add_action('woocommerce_before_add_to_cart_form', 'display_optimized_product_variations');
// 清除产品变体缓存
function clear_product_variation_cache($product_id) {
$cache_key = 'product_variations_' . $product_id;
wp_cache_delete($cache_key, 'woocommerce');
}
add_action('woocommerce_update_product', 'clear_product_variation_cache');
add_action('woocommerce_delete_product', 'clear_product_variation_cache');
对于高流量网站,实施对象缓存可以显著减少数据库查询:
- 使用Redis或Memcached:安装并配置对象缓存扩展
- 配置WooCommerce支持对象缓存:在wp-config.php中添加相应配置
- 使用缓存插件:如W3 Total Cache或WP Rocket
确保WooCommerce相关数据库表有适当的索引:
-- 为WooCommerce订单项表添加索引
ALTER TABLE wp_woocommerce_order_items ADD INDEX order_id (order_id);
-- 为产品元数据表添加索引
ALTER TABLE wp_postmeta ADD INDEX post_id_meta_key (post_id, meta_key(50));
-- 为产品变体属性表添加索引
ALTER TABLE wp_woocommerce_attribute_taxonomies ADD INDEX attribute_name (attribute_name(20));
产品页中的许多JavaScript文件可以延迟加载,直到用户交互时再执行。
/**
* 优化WooCommerce产品页JavaScript加载
* 延迟非关键脚本,异步加载必要脚本
*/
// 延迟加载WooCommerce变体脚本
function defer_woocommerce_variation_script($tag, $handle, $src) {
// 延迟的脚本列表
$scripts_to_defer = array(
'wc-add-to-cart-variation',
'zoom',
'flexslider',
'photoswipe-ui-default'
);
// 异步加载的脚本列表
$scripts_to_async = array(
'wc-single-product',
'wc-add-to-cart'
);
if (in_array($handle, $scripts_to_defer)) {
return str_replace(' src', ' defer src', $tag);
}
if (in_array($handle, $scripts_to_async)) {
return str_replace(' src', ' async src', $tag);
}
return $tag;
}
add_filter('script_loader_tag', 'defer_woocommerce_variation_script', 10, 3);
// 条件加载JavaScript
function conditionally_load_product_scripts() {
// 只在产品页面加载特定脚本
if (is_product()) {
// 移除不必要的脚本
wp_dequeue_script('some-unnecessary-script');
// 延迟加载评价相关脚本
add_filter('script_loader_tag', function($tag, $handle) {
if ($handle === 'comment-reply') {
return str_replace(' src', ' defer src', $tag);
}
return $tag;
}, 10, 2);
}
}
add_action('wp_enqueue_scripts', 'conditionally_load_product_scripts', 100);
/**
* 提取并内联关键CSS,延迟加载非关键CSS
*/
// 提取产品页关键CSS
function get_product_critical_css() {
// 这里应该是从CSS文件中提取的关键CSS代码
// 实际应用中可以使用自动化工具提取
return '
.woocommerce-product-gallery { opacity: 1 !important; }
.product_title { font-size: 24px; margin-bottom: 15px; }
.price { color: #77a464; font-size: 22px; }
.woocommerce-product-details__short-description { margin-bottom: 20px; }
.single_add_to_cart_button {
background: #a46497;
color: white;
padding: 10px 20px;
border: none;
}
';
}
// 内联关键CSS并延迟加载主样式表
function optimize_product_page_css() {
if (is_product()) {
// 获取关键CSS
$critical_css = get_product_critical_css();
// 内联关键CSS
echo '<style id="critical-css">' . $critical_css . '</style>';
// 延迟加载主CSS文件
add_filter('style_loader_tag', function($html, $handle) {
if ($handle === 'woocommerce-general' || $handle === 'woocommerce-layout') {
return str_replace("media='all'", "media='print' onload="this.media='all'"", $html);
}
return $html;
}, 10, 2);
}
}
add_action('wp_head', 'optimize_product_page_css', 1);
/**
* 提取并内联关键CSS,延迟加载非关键CSS
*/
// 提取产品页关键CSS
function get_product_critical_css() {
// 这里应该是从CSS文件中提取的关键CSS代码
// 实际应用中可以使用自动化工具提取
return '
.woocommerce-product-gallery { opacity: 1 !important; }
.product_title { font-size: 24px; margin-bottom: 15px; }
.price { color: #77a464; font-size: 22px; }
.woocommerce-product-details__short-description { margin-bottom: 20px; }
.single_add_to_cart_button {
background: #a46497;
color: white;
padding: 10px 20px;
border: none;
}
';
}
// 内联关键CSS并延迟加载主样式表
function optimize_product_page_css() {
if (is_product()) {
// 获取关键CSS
$critical_css = get_product_critical_css();
// 内联关键CSS
echo '<style id="critical-css">' . $critical_css . '</style>';
// 延迟加载主CSS文件
add_filter('style_loader_tag', function($html, $handle) {
if ($handle === 'woocommerce-general' || $handle === 'woocommerce-layout') {
return str_replace("media='all'", "media='print' onload="this.media='all'"", $html);
}
return $html;
}, 10, 2);
}
}
add_action('wp_head', 'optimize_product_page_css', 1);
对于现代JavaScript,可以使用代码分割技术:
// 动态加载产品变体选择器脚本
if (document.querySelector('.variations_form')) {
import('./product-variation-handler.js')
.then(module => {
module.initVariationHandler();
})
.catch(error => {
console.error('动态加载变体处理器失败:', error);
});
}
// 动态加载产品图库脚本
if (document.querySelector('.woocommerce-product-gallery')) {
import('./product-gallery.js')
.then(module => {
module.initProductGallery();
})
.catch(error => {
console.error('动态加载产品图库失败:', error);
});
}
-
图像优化检查:
- [ ] 启用图像懒加载
- [ ] 转换图像为WebP格式
- [ ] 实施响应式图像
- [ ] 压缩所有产品图片
-
数据库与缓存优化:
- [ ] 实施数据库查询缓存
- [ ] 配置对象缓存(Redis/Memcached)
- [ ] 优化数据库索引
- [ ] 启用页面缓存
-
代码优化:
- [ ] 延迟非关键JavaScript
- [ ] 内联关键CSS
- [ ] 最小化CSS和JavaScript文件
- [ ] 移除未使用的代码
图像优化检查:
- [ ] 启用图像懒加载
- [ ] 转换图像为WebP格式
- [ ] 实施响应式图像
- [ ] 压缩所有产品图片
数据库与缓存优化:
- [ ] 实施数据库查询缓存
- [ ] 配置对象缓存(Redis/Memcached)
- [ ] 优化数据库索引
- [ ] 启用页面缓存
代码优化:
- [ ] 延迟非关键JavaScript
- [ ] 内联关键CSS
- [ ] 最小化CSS和JavaScript文件
- [ ] 移除未使用的代码
实施优化后,使用以下工具测试性能改进:
- Google PageSpeed Insights:全面的性能分析和建议
- GTmetrix:详细的加载时间分析和瀑布图
- WebPageTest:多地点测试和视频录制功能
- Pingdom Tools:简单的速度测试和性能评分
性能优化不是一次性的任务,需要持续监控:
- 设置定期性能检查(每周或每月)
- 监控关键指标:首次内容绘制(FCP)、最大内容绘制(LCP)、首次输入延迟(FID)
- 使用监控工具如New Relic或Google Analytics Site Speed报告
- 定期更新WooCommerce和主题,确保兼容性和性能改进
通过实施上述三个关键技术——优化图像与媒体资源、数据库查询优化与缓存策略、JavaScript与CSS优化,您可以显著提升WooCommerce产品页的加载速度。这些优化不仅改善用户体验,还能直接提高转化率和搜索引擎排名。
记住,性能优化是一个持续的过程。随着WooCommerce的更新、新功能的添加和产品数量的增加,定期重新评估和优化您的网站性能至关重要。从今天开始实施这些技术,您将很快看到网站性能的显著提升和业务指标的积极变化。
最佳实践提示:在实施任何重大更改之前,始终在暂存环境中测试,并确保有完整的网站备份。性能优化应该是一个渐进的过程,一次实施一个更改,测试其效果,然后再进行下一个优化。
服务器配置直接影响WooCommerce产品页的加载性能。以下是最佳实践配置:
# Nginx服务器配置优化示例
# /etc/nginx/nginx.conf 或站点配置文件
http {
# 基础优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 启用Gzip压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;
# 静态资源缓存
location ~* .(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Vary Accept-Encoding;
# 启用Brotli压缩(如果可用)
brotli on;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;
brotli_comp_level 6;
}
# WooCommerce特定规则
location /wp-content/uploads/woocommerce_uploads/ {
expires 1y;
add_header Cache-Control "public";
}
# PHP-FPM优化
location ~ .php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# PHP-FPM性能优化
fastcgi_buffer_size 128k;
fastcgi_buffers 256 16k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
}
}
; php.ini 配置优化
; 适用于WooCommerce的PHP设置
[PHP]
; 内存限制
memory_limit = 256M
; 执行时间
max_execution_time = 300
max_input_time = 300
; 输出缓冲
output_buffering = 4096
implicit_flush = Off
; 会话设置
session.gc_maxlifetime = 1440
session.cookie_lifetime = 0
; OPcache优化(PHP 7.0+)
[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.save_comments=1
; 实时优化配置
opcache.revalidate_freq=0
opcache.validate_timestamps=0 ; 生产环境设为0,开发环境设为1
; php.ini 配置优化
; 适用于WooCommerce的PHP设置
[PHP]
; 内存限制
memory_limit = 256M
; 执行时间
max_execution_time = 300
max_input_time = 300
; 输出缓冲
output_buffering = 4096
implicit_flush = Off
; 会话设置
session.gc_maxlifetime = 1440
session.cookie_lifetime = 0
; OPcache优化(PHP 7.0+)
[opcache]
opcache.enable=1
opcache.memory_consumption=256
opcache.interned_strings_buffer=16
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.save_comments=1
; 实时优化配置
opcache.revalidate_freq=0
opcache.validate_timestamps=0 ; 生产环境设为0,开发环境设为1
# Apache HTTP/2配置示例
# .htaccess 或虚拟主机配置
<IfModule mod_http2.c>
# 启用HTTP/2
Protocols h2 h2c http/1.1
# HTTP/2推送配置
H2Push on
H2PushPriority * after
# 推送关键资源
<FilesMatch ".(css|js)$">
H2PushResource on
</FilesMatch>
# 连接设置
H2MaxSessionStreams 100
H2WindowSize 65535
H2StreamMaxMemSize 128000
</IfModule>
# 启用Brotli压缩
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml application/rss+xml image/svg+xml
</IfModule>
# 资源提示
<IfModule mod_headers.c>
# 预连接关键域名
Header add Link "</wp-content/themes/your-theme/style.css>; rel=preload; as=style"
Header add Link "</wp-includes/js/jquery/jquery.min.js>; rel=preload; as=script"
# DNS预获取
Header add Link "<//fonts.googleapis.com>; rel=dns-prefetch"
Header add Link "<//ajax.googleapis.com>; rel=dns-prefetch"
</IfModule>
# Apache HTTP/2配置示例
# .htaccess 或虚拟主机配置
<IfModule mod_http2.c>
# 启用HTTP/2
Protocols h2 h2c http/1.1
# HTTP/2推送配置
H2Push on
H2PushPriority * after
# 推送关键资源
<FilesMatch ".(css|js)$">
H2PushResource on
</FilesMatch>
# 连接设置
H2MaxSessionStreams 100
H2WindowSize 65535
H2StreamMaxMemSize 128000
</IfModule>
# 启用Brotli压缩
<IfModule mod_brotli.c>
AddOutputFilterByType BROTLI_COMPRESS text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript application/json application/xml application/rss+xml image/svg+xml
</IfModule>
# 资源提示
<IfModule mod_headers.c>
# 预连接关键域名
Header add Link "</wp-content/themes/your-theme/style.css>; rel=preload; as=style"
Header add Link "</wp-includes/js/jquery/jquery.min.js>; rel=preload; as=script"
# DNS预获取
Header add Link "<//fonts.googleapis.com>; rel=dns-prefetch"
Header add Link "<//ajax.googleapis.com>; rel=dns-prefetch"
</IfModule>
/**
* WooCommerce CDN集成配置
* 将静态资源重定向到CDN
*/
class WooCommerce_CDN_Integration {
private $cdn_domain = 'https://cdn.yourdomain.com';
private $excluded_files = array('admin-ajax.php', 'wc-api');
public function __construct() {
// 初始化CDN集成
add_action('init', array($this, 'setup_cdn'));
}
public function setup_cdn() {
// 只在前端启用CDN
if (!is_admin()) {
// 重写静态资源URL
add_filter('wp_get_attachment_url', array($this, 'rewrite_attachment_url'), 10, 2);
add_filter('stylesheet_directory_uri', array($this, 'rewrite_theme_url'));
add_filter('template_directory_uri', array($this, 'rewrite_theme_url'));
add_filter('plugins_url', array($this, 'rewrite_plugins_url'));
// 处理WooCommerce特定资源
add_filter('woocommerce_product_get_image_id', array($this, 'optimize_product_images'));
}
}
public function rewrite_attachment_url($url, $post_id) {
// 只处理图片和文档
$file_type = get_post_mime_type($post_id);
$allowed_types = array('image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf');
if (in_array($file_type, $allowed_types)) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 排除特定文件
foreach ($this->excluded_files as $excluded) {
if (strpos($path, $excluded) !== false) {
return $url;
}
}
// 构建CDN URL
return $this->cdn_domain . $path;
}
return $url;
}
public function rewrite_theme_url($url) {
// 重写主题资源URL
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 只处理CSS、JS和字体文件
if (preg_match('/.(css|js|woff|woff2|ttf|eot|svg)$/', $path)) {
return $this->cdn_domain . $path;
}
return $url;
}
public function rewrite_plugins_url($url) {
// 重写插件资源URL
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 检查是否为WooCommerce资源
if (strpos($path, '/woocommerce/') !== false) {
// 只处理特定文件类型
if (preg_match('/.(css|js|png|jpg|gif|svg)$/', $path)) {
return $this->cdn_domain . $path;
}
}
return $url;
}
public function optimize_product_images($image_id) {
// 为产品图片添加CDN参数
if ($image_id) {
add_filter('wp_get_attachment_image_src', function($image, $id) use ($image_id) {
if ($id == $image_id && isset($image[0])) {
// 添加自动优化参数(适用于支持图片处理的CDN)
$image[0] = add_query_arg(array(
'width' => $image[1],
'height' => $image[2],
'fit' => 'cover',
'quality' => 85,
'format' => 'auto' // 自动选择最佳格式
), $image[0]);
}
return $image;
}, 10, 2);
}
return $image_id;
}
/**
* 生成CDN预取头
*/
public function add_cdn_prefetch_headers() {
if (!is_admin()) {
header("Link: <{$this->cdn_domain}>; rel=preconnect; crossorigin", false);
header("Link: <{$this->cdn_domain}/wp-content/uploads/>; rel=prefetch", false);
header("Link: <{$this->cdn_domain}/wp-content/themes/>; rel=prefetch", false);
}
}
}
// 初始化CDN集成
new WooCommerce_CDN_Integration();
/**
* WooCommerce CDN集成配置
* 将静态资源重定向到CDN
*/
class WooCommerce_CDN_Integration {
private $cdn_domain = 'https://cdn.yourdomain.com';
private $excluded_files = array('admin-ajax.php', 'wc-api');
public function __construct() {
// 初始化CDN集成
add_action('init', array($this, 'setup_cdn'));
}
public function setup_cdn() {
// 只在前端启用CDN
if (!is_admin()) {
// 重写静态资源URL
add_filter('wp_get_attachment_url', array($this, 'rewrite_attachment_url'), 10, 2);
add_filter('stylesheet_directory_uri', array($this, 'rewrite_theme_url'));
add_filter('template_directory_uri', array($this, 'rewrite_theme_url'));
add_filter('plugins_url', array($this, 'rewrite_plugins_url'));
// 处理WooCommerce特定资源
add_filter('woocommerce_product_get_image_id', array($this, 'optimize_product_images'));
}
}
public function rewrite_attachment_url($url, $post_id) {
// 只处理图片和文档
$file_type = get_post_mime_type($post_id);
$allowed_types = array('image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf');
if (in_array($file_type, $allowed_types)) {
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 排除特定文件
foreach ($this->excluded_files as $excluded) {
if (strpos($path, $excluded) !== false) {
return $url;
}
}
// 构建CDN URL
return $this->cdn_domain . $path;
}
return $url;
}
public function rewrite_theme_url($url) {
// 重写主题资源URL
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 只处理CSS、JS和字体文件
if (preg_match('/.(css|js|woff|woff2|ttf|eot|svg)$/', $path)) {
return $this->cdn_domain . $path;
}
return $url;
}
public function rewrite_plugins_url($url) {
// 重写插件资源URL
$parsed_url = parse_url($url);
$path = $parsed_url['path'];
// 检查是否为WooCommerce资源
if (strpos($path, '/woocommerce/') !== false) {
// 只处理特定文件类型
if (preg_match('/.(css|js|png|jpg|gif|svg)$/', $path)) {
return $this->cdn_domain . $path;
}
}
return $url;
}
public function optimize_product_images($image_id) {
// 为产品图片添加CDN参数
if ($image_id) {
add_filter('wp_get_attachment_image_src', function($image, $id) use ($image_id) {
if ($id == $image_id && isset($image[0])) {
// 添加自动优化参数(适用于支持图片处理的CDN)
$image[0] = add_query_arg(array(
'width' => $image[1],
'height' => $image[2],
'fit' => 'cover',
'quality' => 85,
'format' => 'auto' // 自动选择最佳格式
), $image[0]);
}
return $image;
}, 10, 2);
}
return $image_id;
}
/**
* 生成CDN预取头
*/
public function add_cdn_prefetch_headers() {
if (!is_admin()) {
header("Link: <{$this->cdn_domain}>; rel=preconnect; crossorigin", false);
header("Link: <{$this->cdn_domain}/wp-content/uploads/>; rel=prefetch", false);
header("Link: <{$this->cdn_domain}/wp-content/themes/>; rel=prefetch", false);
}
}
}
// 初始化CDN集成
new WooCommerce_CDN_Integration();
// 边缘计算示例:在CDN边缘处理产品变体计算
// 这个示例展示如何使用Cloudflare Workers处理变体价格计算
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// 只处理产品变体API请求
const url = new URL(request.url)
if (url.pathname.includes('/wc-api/variations/')) {
return handleVariationRequest(request, url)
}
// 其他请求直接传递
return fetch(request)
}
async function handleVariationRequest(request, url) {
// 从URL获取产品ID和属性
const productId = url.pathname.split('/').pop()
const searchParams = new URLSearchParams(url.search)
// 构建缓存键
const cacheKey = `variation_${productId}_${Array.from(searchParams.entries()).sort().toString()}`
// 检查边缘缓存
const cache = caches.default
let response = await cache.match(request)
if (!response) {
// 缓存未命中,从源站获取
response = await fetch(request.clone())
if (response.status === 200) {
// 克隆响应以修改
const newResponse = new Response(response.body, response)
// 添加边缘缓存头
newResponse.headers.set('Cache-Control', 'public, max-age=3600')
newResponse.headers.set('CDN-Cache-Control', 'public, max-age=3600')
newResponse.headers.set('Vary', 'Accept-Encoding, User-Agent')
// 存储到边缘缓存
event.waitUntil(cache.put(request, newResponse.clone()))
return newResponse
}
}
return response
}
// 边缘计算:实时价格计算
async function calculateDynamicPrice(productData, variationAttributes) {
// 从边缘KV存储获取价格规则
const pricingRules = await PRICING_KV.get('pricing_rules', 'json')
// 应用价格规则
let basePrice = productData.price
let finalPrice = basePrice
// 检查批量折扣
if (pricingRules.bulk_discounts) {
for (const rule of pricingRules.bulk_discounts) {
if (variationAttributes.quantity >= rule.min_quantity) {
finalPrice = basePrice * (1 - rule.discount_percent / 100)
break
}
}
}
// 检查会员折扣
if (pricingRules.member_discounts && variationAttributes.is_member) {
finalPrice *= (1 - pricingRules.member_discounts.percent / 100)
}
return {
price: finalPrice.toFixed(2),
original_price: basePrice.toFixed(2),
discount: ((basePrice - finalPrice) / basePrice * 100).toFixed(1)
}
}
// 边缘计算示例:在CDN边缘处理产品变体计算
// 这个示例展示如何使用Cloudflare Workers处理变体价格计算
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// 只处理产品变体API请求
const url = new URL(request.url)
if (url.pathname.includes('/wc-api/variations/')) {
return handleVariationRequest(request, url)
}
// 其他请求直接传递
return fetch(request)
}
async function handleVariationRequest(request, url) {
// 从URL获取产品ID和属性
const productId = url.pathname.split('/').pop()
const searchParams = new URLSearchParams(url.search)
// 构建缓存键
const cacheKey = `variation_${productId}_${Array.from(searchParams.entries()).sort().toString()}`
// 检查边缘缓存
const cache = caches.default
let response = await cache.match(request)
if (!response) {
// 缓存未命中,从源站获取
response = await fetch(request.clone())
if (response.status === 200) {
// 克隆响应以修改
const newResponse = new Response(response.body, response)
// 添加边缘缓存头
newResponse.headers.set('Cache-Control', 'public, max-age=3600')
newResponse.headers.set('CDN-Cache-Control', 'public, max-age=3600')
newResponse.headers.set('Vary', 'Accept-Encoding, User-Agent')
// 存储到边缘缓存
event.waitUntil(cache.put(request, newResponse.clone()))
return newResponse
}
}
return response
}
// 边缘计算:实时价格计算
async function calculateDynamicPrice(productData, variationAttributes) {
// 从边缘KV存储获取价格规则
const pricingRules = await PRICING_KV.get('pricing_rules', 'json')
// 应用价格规则
let basePrice = productData.price
let finalPrice = basePrice
// 检查批量折扣
if (pricingRules.bulk_discounts) {
for (const rule of pricingRules.bulk_discounts) {
if (variationAttributes.quantity >= rule.min_quantity) {
finalPrice = basePrice * (1 - rule.discount_percent / 100)
break
}
}
}
// 检查会员折扣
if (pricingRules.member_discounts && variationAttributes.is_member) {
finalPrice *= (1 - pricingRules.member_discounts.percent / 100)
}
return {
price: finalPrice.toFixed(2),
original_price: basePrice.toFixed(2),
discount: ((basePrice - finalPrice) / basePrice * 100).toFixed(1)
}
}
/**
* 智能缓存失效系统
* 根据产品更新自动清除相关缓存
*/
class WooCommerce_Smart_Cache_Invalidation {
private $cache_groups = array(
'product_data',
'product_queries',
'related_products',
'product_html'
);
public function __construct() {
// 产品更新时清除缓存
add_action('save_post_product', array($this, 'invalidate_product_cache'), 10, 3);
add_action('woocommerce_update_product', array($this, 'invalidate_product_cache_complete'));
// 订单相关操作
add_action('woocommerce_new_order', array($this, 'invalidate_stock_cache'));
add_action('woocommerce_order_status_changed', array($this, 'invalidate_stock_cache'));
// 评论/评价更新
add_action('comment_post', array($this, 'invalidate_review_cache'), 10, 3);
add_action('wp_update_comment_count', array($this, 'invalidate_review_cache_bulk'));
}
public function invalidate_product_cache($post_id, $post, $update) {
if ($post->post_type !== 'product' || wp_is_post_revision($post_id)) {
return;
}
// 清除产品数据缓存
$this->clear_product_specific_cache($post_id);
// 清除相关产品缓存
$this->clear_related_products_cache($post_id);
// 清除分类页面缓存
$this->clear_category_cache($post_id);
// 延迟清除HTML缓存(避免并发问题)
wp_schedule_single_event(time() + 5, 'woocommerce_delayed_cache_clear', array($post_id));
}
private function clear_product_specific_cache($product_id) {
$cache_keys = array(
"product_{$product_id}_full",
"product_{$product_id}_variations",
"product_{$product_id}_attributes",
"product_{$product_id}_html"
);
foreach ($cache_keys as $key) {
foreach ($this->cache_groups as $group) {
wp_cache_delete($key, $group);
}
}
// 清除对象缓存
if (function_exists('wp_cache_flush_group')) {
foreach ($this->cache_groups as $group) {
wp_cache_flush_group($group);
}
}
}
private function clear_related_products_cache($product_id) {
// 获取相关产品ID
$related_ids = wc_get_related_products($product_id);
foreach ($related_ids as $related_id) {
wp_cache_delete("product_{$related_id}_related", 'product_queries');
}
// 清除全局相关产品缓存
wp_cache_delete('all_related_products', 'product_queries');
}
private function clear_category_cache($product_id) {
$terms = wp_get_post_terms($product_id, 'product_cat');
foreach ($terms as $term) {
$cache_key = "category_{$term->term_id}_products";
wp_cache_delete($cache_key, 'product_queries');
// 清除分类页面HTML缓存
$html_cache_key = "category_{$term->term_id}_html";
wp_cache_delete($html_cache_key, 'product_html');
}
}
public function invalidate_stock_cache($order_id) {
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// 获取订单中的所有产品
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
// 清除库存缓存
wp_cache_delete("product_{$product_id}_stock", 'product_data');
wp_cache_delete("product_{$product_id}_availability", 'product_data');
// 清除变体库存缓存
if ($item->get_variation_id()) {
wp_cache_delete("variation_{$item->get_variation_id()}_stock", 'product_data');
}
}
}
/**
* 部分缓存更新(只更新变化的部分)
*/
public function partial_cache_update($product_id, $updated_fields) {
$product_data = wp_cache_get("product_{$product_id}_full", 'product_data');
if ($product_data) {
// 只更新变化的字段
foreach ($updated_fields as $field => $value) {
$product_data[$field] = $value;
}
// 更新缓存
wp_cache_set("product_{$product_id}_full", $product_data, 'product_data', HOUR_IN_SECONDS);
// 生成部分HTML更新
$this->generate_partial_html_update($product_id, $updated_fields);
}
}
private function generate_partial_html_update($product_id, $updated_fields) {
// 只重新生成变化的部分HTML
$partial_html = '';
if (isset($updated_fields['price'])) {
ob_start();
woocommerce_template_single_price();
$partial_html .= '<div id="product-price">' . ob_get_clean() . '</div>';
}
if (isset($updated_fields['stock_status'])) {
ob_start();
woocommerce_template_single_stock();
$partial_html .= '<div id="product-stock">' . ob_get_clean() . '</div>';
}
// 存储部分HTML更新
if (!empty($partial_html)) {
wp_cache_set(
"product_{$product_id}_partial_html",
$partial_html,
'product_html',
300 // 5分钟过期
);
}
}
}
/**
* 智能缓存失效系统
* 根据产品更新自动清除相关缓存
*/
class WooCommerce_Smart_Cache_Invalidation {
private $cache_groups = array(
'product_data',
'product_queries',
'related_products',
'product_html'
);
public function __construct() {
// 产品更新时清除缓存
add_action('save_post_product', array($this, 'invalidate_product_cache'), 10, 3);
add_action('woocommerce_update_product', array($this, 'invalidate_product_cache_complete'));
// 订单相关操作
add_action('woocommerce_new_order', array($this, 'invalidate_stock_cache'));
add_action('woocommerce_order_status_changed', array($this, 'invalidate_stock_cache'));
// 评论/评价更新
add_action('comment_post', array($this, 'invalidate_review_cache'), 10, 3);
add_action('wp_update_comment_count', array($this, 'invalidate_review_cache_bulk'));
}
public function invalidate_product_cache($post_id, $post, $update) {
if ($post->post_type !== 'product' || wp_is_post_revision($post_id)) {
return;
}
// 清除产品数据缓存
$this->clear_product_specific_cache($post_id);
// 清除相关产品缓存
$this->clear_related_products_cache($post_id);
// 清除分类页面缓存
$this->clear_category_cache($post_id);
// 延迟清除HTML缓存(避免并发问题)
wp_schedule_single_event(time() + 5, 'woocommerce_delayed_cache_clear', array($post_id));
}
private function clear_product_specific_cache($product_id) {
$cache_keys = array(
"product_{$product_id}_full",
"product_{$product_id}_variations",
"product_{$product_id}_attributes",
"product_{$product_id}_html"
);
foreach ($cache_keys as $key) {
foreach ($this->cache_groups as $group) {
wp_cache_delete($key, $group);
}
}
// 清除对象缓存
if (function_exists('wp_cache_flush_group')) {
foreach ($this->cache_groups as $group) {
wp_cache_flush_group($group);
}
}
}
private function clear_related_products_cache($product_id) {
// 获取相关产品ID
$related_ids = wc_get_related_products($product_id);
foreach ($related_ids as $related_id) {
wp_cache_delete("product_{$related_id}_related", 'product_queries');
}
// 清除全局相关产品缓存
wp_cache_delete('all_related_products', 'product_queries');
}
private function clear_category_cache($product_id) {
$terms = wp_get_post_terms($product_id, 'product_cat');
foreach ($terms as $term) {
$cache_key = "category_{$term->term_id}_products";
wp_cache_delete($cache_key, 'product_queries');
// 清除分类页面HTML缓存
$html_cache_key = "category_{$term->term_id}_html";
wp_cache_delete($html_cache_key, 'product_html');
}
}
public function invalidate_stock_cache($order_id) {
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// 获取订单中的所有产品
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
// 清除库存缓存
wp_cache_delete("product_{$product_id}_stock", 'product_data');
wp_cache_delete("product_{$product_id}_availability", 'product_data');
// 清除变体库存缓存
if ($item->get_variation_id()) {
wp_cache_delete("variation_{$item->get_variation_id()}_stock", 'product_data');
}
}
}
/**
* 部分缓存更新(只更新变化的部分)
*/
public function partial_cache_update($product_id, $updated_fields) {
$product_data = wp_cache_get("product_{$product_id}_full", 'product_data');
if ($product_data) {
// 只更新变化的字段
foreach ($updated_fields as $field => $value) {
$product_data[$field] = $value;
}
// 更新缓存
wp_cache_set("product_{$product_id}_full", $product_data, 'product_data', HOUR_IN_SECONDS);
// 生成部分HTML更新
$this->generate_partial_html_update($product_id, $updated_fields);
}
}
private function generate_partial_html_update($product_id, $updated_fields) {
// 只重新生成变化的部分HTML
$partial_html = '';
if (isset($updated_fields['price'])) {
ob_start();
woocommerce_template_single_price();
$partial_html .= '<div id="product-price">' . ob_get_clean() . '</div>';
}
if (isset($updated_fields['stock_status'])) {
ob_start();
woocommerce_template_single_stock();
$partial_html .= '<div id="product-stock">' . ob_get_clean() . '</div>';
}
// 存储部分HTML更新
if (!empty($partial_html)) {
wp_cache_set(
"product_{$product_id}_partial_html",
$partial_html,
'product_html',
300 // 5分钟过期
);
}
}
}


