DebugBear Blog
29 Apr 2019

Measuring when images are displayed with the experimental Element Timing API

The Element Timing API lets you track when images appear on the screen.

While this could be done with JavaScript, the Element Timing API is more accurate and doesn't require blocking JavaScript execution.

Note that the API is experimental, will change, and might be removed in the future. You need to sign up for an origin trial to use it.

How the Element Timing API works

The browser will create an PerformanceElementTiming metric for an image if it either:

  • has an elementtiming="some-identifier" attribute
  • takes up more than 15% of the viewport

Note that the automatic image registration means that depending on screen size the performance entry may or may not be created.

The Element Timing API also works for background images.

What does the timing entry look like?

We'll get a metric like this when calling performance.getEntriesByType("element"):

{
    "name": "http://localhost:8080/public/head-white-outline.png",
    "id": "element-id",
    "entryType": "element",
    "startTime": 90.68500006105751,
    "duration": 0,
    "identifier": "some-identifier",
    "naturalHeight": 73,
    "naturalWidth": 70,
    "intersectionRect": { "x": 253, "y": 30, "width": 71, "height": 73 }
}

The startTime is the time in milliseconds before the image is displayed, relative to when the document started loading.

Trying it out

Registering for the origin trial

Chrome uses a system called origin trials as a replacement for vendor prefixes. You need to sign up for the "Element Timing for Images" origin trial. Localhost can be used as the web origin address as well.

Signup form for the element timing api origin trial

You'll then get a registration token that you can include in a meta tag on your site:

<meta http-equiv="origin-trial" content="TOKEN_YOU_GOT">

This will enable the API on the provided domain. When loading the page performance.clearElementTimings should be defined.

Using it in the browser

Add the elementtiming attribute to an element:

<img src="/public/head-white-outline.png" elementtiming="some-identifier" />

Finally run performance.getEntriesByType("element") to read the results.

Troubleshooting

If the image you're interested in is hosted on a CDN rather than your site domain you'll need to set a Timing-Allow-Origin header.

Also make sure that the img element is created with the final image URL, rather than a placeholder image. Otherwise Chrome will track how the placeholder image was loaded instead.

DebugBear is a website monitoring tool built for front-end developers.

Track performance metrics and Lighthouse scores in CI and production.

Learn more.

Get new articles on web performance and debugging by email.

© 2019 DebugBear Ltd