Back to Blog

Detecting Fetch Requests on a Document using PerformanceObserver

K
Karan Goyal
--2 min read

Learn how to detect fetch requests on a document using the PerformanceObserver API.

Detecting Fetch Requests on a Document using PerformanceObserver

Introduction

Detecting fetch requests on a document can be useful for various purposes, such as logging, analytics, or initializing other libraries. In this blog post, we'll explore how to achieve this using the PerformanceObserver API.

What is PerformanceObserver?

The PerformanceObserver API allows you to observe performance metrics of your web application. It provides a way to monitor various performance-related events, such as resource loading, paint timing, and more.

Detecting Fetch Requests

To detect fetch requests, we'll create a PerformanceObserver instance and observe the 'resource' entry type. Here's the code:

javascript
const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.initiatorType === "fetch") {
      console.log('Fetch request detected to', entry.name);
      // For loading aos dynamically
      // AOS.init();
    }
  }
});

observer.observe({
  entryTypes: ["resource"]
});

Let's break down the code:

  1. We create a new PerformanceObserver instance, passing a callback function that will be executed when new performance entries are available.
  2. Inside the callback, we iterate over the list of performance entries using list.getEntries().
  3. We check if the initiatorType property of each entry is equal to 'fetch', indicating that the resource was loaded using the Fetch API.
  4. If it's a fetch request, we log a message to the console with the URL of the request.
  5. Finally, we start observing performance entries of type 'resource' using observer.observe().

Usage Examples

You can use this code to detect fetch requests for various purposes, such as:

  • Logging fetch requests for analytics or debugging purposes
  • Initializing other libraries or plugins dynamically when a fetch request is made
  • Monitoring fetch request performance metrics

Conclusion

In this blog post, we've learned how to detect fetch requests on a document using the PerformanceObserver API. By observing performance entries of type 'resource' and checking the initiatorType property, we can identify fetch requests and perform actions accordingly.

Tags

#PerformanceObserver#Fetch API#Web Development#JavaScript

Share this article

Comments (0)

Leave a Comment

0/2000

No comments yet. Be the first to share your thoughts!