Detecting Fetch Requests on a Document using PerformanceObserver
Learn how to detect fetch requests on a document using the PerformanceObserver API.

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:
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:
- We create a new PerformanceObserver instance, passing a callback function that will be executed when new performance entries are available.
- Inside the callback, we iterate over the list of performance entries using
list.getEntries(). - We check if the
initiatorTypeproperty of each entry is equal to 'fetch', indicating that the resource was loaded using the Fetch API. - If it's a fetch request, we log a message to the console with the URL of the request.
- 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
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!