3 min read

The Good One For Performance Observer-elementtiming Attribute in HTML

Table of Contents

Introduction

Last month, I spent time thoroughly studying the PerformanceObserver API related to performance monitoring.

However, after exploring it, I couldn’t find a way to measure the loading time of a specific image or the rendering time of a particular element. Did I miss something?

It turns out I did!

Surprisingly, even though the PerformanceObserver API is entirely based on JavaScript methods, measuring an element’s rendering and loading time relies on an HTML attribute — elementtiming, which enables performance tracking directly through markup.


A Guide to Understanding the elementtiming Attribute

The elementtiming attribute can be applied to any element with visual or textual content, including background-image and even video elements.

It’s like telling the browser:

“Hey, browser, I’m really interested in these specific elements. Track them closely and keep a watchful eye!”

When this happens, the browser will record various details about these elements, such as their loading time and rendering time.

By combining this with the PerformanceObserver API, we can access this information in real-time.

Example Explanation

Suppose there are two example HTML elements on the page, as shown in the following code example.

<img src="https://raw.githubusercontent.com/trevortylerlee/n1/main/n1.jpeg" elementtiming="image">
  <p elementtiming="text">I'm content</p>

At this point, the browser will monitor the element timing information for the two elements marked with image and text.

By executing the code below, we can obtain this information.

const observer = new PerformanceObserver(list => {
  let entries = list.getEntries().forEach(function (entry) {
     console.log(entry);
  });
});
observer.observe({ 
  entryTypes: ['element'] 
});

For example, the output in the Chrome console might look like this, as shown in the following screenshot. It displays not only the element’s size and position but also the time when rendering started, as well as the loading time (for image elements).

p

Awesome!

From now on, when we encounter page rendering lags, we can now precisely identify which element is causing the delay in rendering.

Compatibility

p

The elementtiming attribute is great, but unfortunately, it is not supported by Safari as of now.

But after thinking it through, when it comes to performance testing and troubleshooting, having support from just one browser is actually enough.

If the performance is poor in Chrome, it’s usually poor in Safari as well.

So just go ahead and use it without worries!