网站优化:如何为指定第三方资源URL配置浏览器缓存?
Hey there! Let's walk through how to set up browser caching for those third-party scripts your audit flagged. The exact setup depends on your web server environment, but I'll cover the most common approaches below.
Quick heads-up: Most of these third-party resources (Google Tag Manager, Facebook SDK, etc.) already have their own caching rules set by their providers. But if your tool says you need longer or specific cache times, you’ve got two solid options: proxy the resources through your own server (so you control the cache headers) or use a Service Worker to handle caching on the client side. Let’s break both down.
Proxying lets you serve these third-party scripts through your own domain, giving you full control over cache headers. Here’s how to do it for Apache and Nginx:
Apache (using .htaccess)
First, make sure mod_proxy and mod_proxy_http are enabled in your Apache server config. Then add these rules to your site’s .htaccess file:
# Proxy each third-party script to your domain ProxyPass "/gtag/js" "https://www.googletagmanager.com/gtag/js?id=UA-40514212-1" ProxyPassReverse "/gtag/js" "https://www.googletagmanager.com/gtag/js?id=UA-40514212-1" ProxyPass "/facebook-sdk.js" "https://connect.facebook.net/sk_SK/sdk.js" ProxyPassReverse "/facebook-sdk.js" "https://connect.facebook.net/sk_SK/sdk.js" ProxyPass "/adsbygoogle.js" "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" ProxyPassReverse "/adsbygoogle.js" "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" ProxyPass "/analytics.js" "https://www.google-analytics.com/analytics.js" ProxyPassReverse "/analytics.js" "https://www.google-analytics.com/analytics.js" # Set custom cache headers for proxied scripts <FilesMatch "^(gtag/js|facebook-sdk.js|adsbygoogle.js|analytics.js)$"> ExpiresActive On # Google Tag Manager: 15 minutes (900 seconds) <If "%{REQUEST_URI} =~ /gtag/js/"> ExpiresDefault "access plus 15 minutes" Header set Cache-Control "public, max-age=900" </If> # Facebook SDK: 20 minutes (1200 seconds) <If "%{REQUEST_URI} =~ /facebook-sdk.js/"> ExpiresDefault "access plus 20 minutes" Header set Cache-Control "public, max-age=1200" </If> # Ads by Google: 60 minutes (3600 seconds) <If "%{REQUEST_URI} =~ /adsbygoogle.js/"> ExpiresDefault "access plus 60 minutes" Header set Cache-Control "public, max-age=3600" </If> # Google Analytics: 2 hours (7200 seconds) <If "%{REQUEST_URI} =~ /analytics.js/"> ExpiresDefault "access plus 2 hours" Header set Cache-Control "public, max-age=7200" </If> </FilesMatch>
After adding this, update your site’s script tags to point to your proxied paths (e.g., /gtag/js instead of the full Google URL).
Nginx
Add these rules to your Nginx server block config (usually in /etc/nginx/sites-available/your-site):
# Proxy and cache Google Tag Manager location /gtag/js { proxy_pass https://www.googletagmanager.com/gtag/js?id=UA-40514212-1; proxy_cache_valid 200 15m; add_header Cache-Control "public, max-age=900"; } # Proxy and cache Facebook SDK location /facebook-sdk.js { proxy_pass https://connect.facebook.net/sk_SK/sdk.js; proxy_cache_valid 200 20m; add_header Cache-Control "public, max-age=1200"; } # Proxy and cache Ads by Google location /adsbygoogle.js { proxy_pass https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js; proxy_cache_valid 200 60m; add_header Cache-Control "public, max-age=3600"; } # Proxy and cache Google Analytics location /analytics.js { proxy_pass https://www.google-analytics.com/analytics.js; proxy_cache_valid 200 2h; add_header Cache-Control "public, max-age=7200"; }
Like with Apache, update your script tags to use these local proxied paths.
If proxying isn’t feasible (e.g., you don’t have server access), you can use a Service Worker to intercept requests to these scripts and cache them for your desired durations. Here’s a basic implementation:
First, create a service-worker.js file in your site’s root:
const CACHE_CONFIG = [ { url: 'https://www.googletagmanager.com/gtag/js?id=UA-40514212-1', cacheName: 'gtag-cache-v1', maxAgeMs: 900000 // 15 minutes in milliseconds }, { url: 'https://connect.facebook.net/sk_SK/sdk.js', cacheName: 'facebook-cache-v1', maxAgeMs: 1200000 // 20 minutes }, { url: 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js', cacheName: 'adsbygoogle-cache-v1', maxAgeMs: 3600000 // 60 minutes }, { url: 'https://www.google-analytics.com/analytics.js', cacheName: 'analytics-cache-v1', maxAgeMs: 7200000 // 2 hours } ]; self.addEventListener('fetch', (event) => { const match = CACHE_CONFIG.find(item => event.request.url.startsWith(item.url)); if (!match) return; event.respondWith( caches.open(match.cacheName).then(cache => { return cache.match(event.request).then(cachedResponse => { // Return cached response if it's still fresh if (cachedResponse) { const cachedTime = new Date(cachedResponse.headers.get('date')).getTime(); if (Date.now() - cachedTime < match.maxAgeMs) { return cachedResponse; } } // Fetch fresh version and update cache return fetch(event.request).then(networkResponse => { cache.put(event.request, networkResponse.clone()); return networkResponse; }); }); }) ); });
Then register the Service Worker in your main HTML file:
<script> if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('/service-worker.js') .then(reg => console.log('Service Worker registered:', reg)) .catch(err => console.log('Service Worker registration failed:', err)); }); } </script>
- Provider Terms: Double-check the terms of service for each provider (Google, Facebook) to make sure proxying/caching their scripts doesn’t violate any rules. Most allow reasonable caching, but it’s better to confirm.
- Cache Busting: If these scripts update frequently, use versioned cache names (e.g.,
gtag-cache-v2) in your Service Worker or add query params to proxied URLs to force users to get the latest version when needed. - Test It: Use your browser’s DevTools (Network tab) to verify that the
Cache-Controlheaders match your desired durations for these resources after setup.
内容的提问来源于stack exchange,提问作者ShakedHead

