PerformanceResourceTiming: responseStatus property

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Note: This feature is available in Web Workers.

Thuộc tính chỉ đọc responseStatus biểu thị mã trạng thái phản hồi HTTP được trả về khi tìm nạp tài nguyên.

Thuộc tính này ánh xạ tới Response.status từ Fetch API.

Giá trị

Thuộc tính responseStatus có thể có các giá trị sau:

Ví dụ

Kiểm tra xem có trúng cache hay không

Thuộc tính responseStatus có thể dùng để kiểm tra tài nguyên được cache với mã phản hồi 304 Not Modified.

Ví dụ dùng PerformanceObserver, thông báo các performance entry resource mới khi chúng được ghi trong performance timeline của trình duyệt. Dùng tùy chọn buffered để truy cập các entry từ trước khi observer được tạo.

js
const observer = new PerformanceObserver((list) => {
  list.getEntries().forEach((entry) => {
    if (entry.responseStatus === 304) {
      console.log(`${entry.name} was loaded from cache`);
    }
  });
});

observer.observe({ type: "resource", buffered: true });

Ví dụ dùng Performance.getEntriesByType(), chỉ hiển thị các performance entry resource đang có trong performance timeline tại thời điểm bạn gọi phương thức này:

js
const resources = performance.getEntriesByType("resource");
resources.forEach((entry) => {
  if (entry.responseStatus === 304) {
    console.log(`${entry.name} was loaded from cache`);
  }
});

Ngoài ra, nếu responseStatus không khả dụng, bạn có thể kiểm tra xem thuộc tính transferSize có trả về 0 hay không.

Mã trạng thái phản hồi cross-origin

Nếu giá trị của thuộc tính responseStatus0, tài nguyên có thể là một yêu cầu cross-origin. Để hiển thị mã trạng thái phản hồi cross-origin, cần đặt tiêu đề phản hồi HTTP CORS Access-Control-Allow-Origin.

Ví dụ, để cho phép https://mdn.go-mizu.dev xem mã trạng thái phản hồi, tài nguyên cross-origin nên gửi:

http
Access-Control-Allow-Origin: https://mdn.go-mizu.dev

Thông số kỹ thuật

Specification
Resource Timing
# dom-performanceresourcetiming-responsestatus

Tương thích trình duyệt

Xem thêm