Hemanth's Scribes

web

DOM Element Timing API

Author Photo

Hemanth HM

Thumbnail

Measuring and monitoring the rendering timestamps of DOM elements is an important measure to improve and avoid regressions in page loads.

The Element Timing API helps us to measure this with ease and it supports the following elements:

  • img elements
  • image elements inside an SVG
  • video element’s poster image
  • Elements with a background-image
  • Groups of text nodes

Usage

Make sure the DOM element of interest has the elementtiming content attribute:

<img src="" elementtiming="cat-pic" />
<p elementtiming="imp-doc">I need to watch this</p>
<!-- So on -->

## Observe the Element
javascript
const observer = new PerformanceObserver(list => {
  let perfEntries = list.getEntries().forEach(function(entry) {
    if (entry.identifier) {
      if (entry.renderTime) {
        console.log(`${entry.renderTime}ms to render!`);
      } else {
        console.log(`${entry.loadTime}ms to load!`);
      }
    }
  });
});

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

renderTime and loadTime will be DOMHighResTimeStamp time stamp in milliseconds.

Note: renderTime may not be available if the element is an image and it’s loaded cross-origin without the Timing-Allow-Origin header.

DEMO

#javascript#web-api#performance
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.