Cookie Consent by Free Privacy Policy Generator

How to Cache a Third-Party Script Using a Cloudflare Worker

In this tutorial, I’ll guide you through the process of caching a third-party JavaScript file (in this case, a script from the Web Vitals library) using a Cloudflare Worker.

1725567919474.png


This approach allows you to serve the script directly from your domain, reducing the dependency on third-party servers and improving your site's performance by leveraging Cloudflare's edge caching.

Why Cache Third-Party Scripts?​

Third-party scripts can often slow down your website by introducing external dependencies. If these scripts take too long to load or the external server is down, your site can be affected. By caching the script at Cloudflare’s edge, we not only speed up the script's delivery but also reduce reliance on third-party servers.

In this example, we’ll be using the Web Vitals measurement script from unpkg.com. It is a popular web component for measuring a site's Core Web Vitals metrics. We shall be caching the script and serving it from our own domain.

Step 1: The Web Vitals Script​

First, let’s understand the script we want to cache and serve. The Web Vitals library helps us measure key performance metrics like CLS (Cumulative Layout Shift), FID (First Input Delay), and LCP (Largest Contentful Paint).

Here’s how you would normally import the Web Vitals script in your HTML:

Code:
<script type="module">
  import {
    onCLS,
    onFID,
    onLCP,
  } from 'https://unpkg.com/web-vitals@3.5.2/dist/web-vitals.attribution.js?module';

  onCLS(console.log);
  onFID(console.log);
  onLCP(console.log);
</script>

This code fetches the Web Vitals script from unpkg.com every time the page loads. Now, instead of relying on unpkg.com for each request, we’ll use a Cloudflare Worker to cache this file and serve it directly from our domain.

Step 2: Creating a new Cloudflare Worker​

work2-2.jpg

Head over to your Cloudflare Dashboard and create a new Worker. Give it a suitable name. In our case, we named it "cwv" (Core Web Vitals). Ignore the placeholder JS code for now; go ahead and click deploy.

On the next screen, click edit code.
1725566446694.png


Step 3: Writing the Worker Script​

workers3.jpg


Now, let’s write the Worker code that will handle caching and serving the Web Vitals script.

Code:
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
  const url = new URL(request.url);
  // Check if the request is for /web-vitals.js on your domain
  if (url.pathname === '/web-vitals.js') {
    // Use Cloudflare's cache storage
    let cache = caches.default;
    let cachedResponse = await cache.match(request);
    // If the script is in the cache, serve it from cache
    if (cachedResponse) {
      console.log('Serving cached web-vitals.js from Cloudflare');
      return new Response(cachedResponse.body, {
        headers: { 'Content-Type': 'application/javascript' }  // Ensure the correct content type
      });
    }
    // If not cached, fetch it from unpkg.com
    const externalUrl = 'https://unpkg.com/web-vitals@3.5.2/dist/web-vitals.attribution.js?module';
    let fetchResponse = await fetch(externalUrl);
    // Check if the fetch was successful
    if (fetchResponse.ok) {
      console.log('Caching the new web-vitals.js file from unpkg');
      // Cache the response for future use
      await cache.put(request, fetchResponse.clone());
      // Return the fetched response with the correct Content-Type header
      return new Response(fetchResponse.body, {
        status: fetchResponse.status,
        statusText: fetchResponse.statusText,
        headers: { 'Content-Type': 'application/javascript' }
      });
    } else {
      return new Response('Failed to fetch the script from unpkg', { status: 500 });
    }
  }
  // For all other requests, fetch as usual
  return fetch(request);
}


Step 4: How the Worker Script Works​

Let’s break down the functionality of this Worker script:

  1. Intercepting Requests: The addEventListener('fetch') listens for requests made to your domain. In this case, it intercepts requests to /web-vitals.js.
  2. Checking the Cache: When the request is received, the script checks Cloudflare’s cache to see if the Web Vitals file has already been stored. If it’s cached, it’s served immediately, cutting down load times.
  3. Fetching from the External Source: If the script is not in the cache, the Worker fetches it from unpkg.com and stores a copy in Cloudflare's cache for future requests.
  4. Serving the Response: After fetching (or retrieving from cache), the Worker serves the script back to the user with the appropriate Content-Type header to ensure it's treated as JavaScript.

Step 5: How the Worker Script Works​

Now that we have saved the worker script, it is time to put it to work.

1725566548408.png


Head to Cloudflare dashboard > Your Website > Worker Routes. Create a new route named web-vitals.js and map it to the newly created worker we have named CVW. See the screenshot above. Save it, give it a minute or so and then navigate to https://yourdomain.com/web-vitals.js. Can you now see the cached version of https://unpkg.com/web-vitals@3.5.2/dist/web-vitals.attribution.js?module on your own domain?



Step 6: Updating Your HTML to Use the Cached Script​

1725567127613.png


Now that you’ve set up the Worker, you can change the script tag in your HTML to reference the cached file on your own domain:

Code:
<script type="module">
  import {
    onCLS,
    onFID,
    onLCP,
  } from 'https://yourdomain.com/web-vitals.js';  <!-- cached on your domain -->

  onCLS(console.log);
  onFID(console.log);
  onLCP(console.log);
</script>


Benefits of This Approach​

By caching and serving the Web Vitals script through Cloudflare’s Edge, you gain benefits such as:
  • Improved Load Times: Once cached, the script is served from Cloudflare’s global network, reducing latency.
  • Reliability: You reduce reliance on external services like unpkg.com, ensuring your site’s performance doesn’t depend on third-party availability.
  • Optimised SEO Performance: Faster load times and improved reliability positively impact Core Web Vitals, which are key metrics for SEO and user experience.
 
Last edited:
Back
Top