Skip to content

Instantly share code, notes, and snippets.

@noamr
Last active April 24, 2024 18:42
Show Gist options
  • Save noamr/b6e77e2c8a04e4362983477c9a8f727c to your computer and use it in GitHub Desktop.
Save noamr/b6e77e2c8a04e4362983477c9a8f727c to your computer and use it in GitHub Desktop.
Paint timestamp
const next_frame = () => Promise(resolve => requestAnimationFrame(ts => resolve(ts));
async function get_img_presentation_time(img) {
// Wait until image is fully loaded
await new Promise(resolve => img.complete ? resolve() : img.addEventListener("load", resolve))
let frame_timestamp = await next_frame();
// Wait until we have the frame timestamp soonest after the image was decoded.
// Note that because of main-thread scheduling the implementation might be slightly different than the polyfill
let decoded = false;
img.decode().then(() => {
decoded = true;
});
while (!decoded) {
frame_timestamp = await next_frame();
}
return frame_timestamp;
}
@mmocny
Copy link

mmocny commented Apr 23, 2024

I think conceptually this is useful.

I think there are certain expectations here:

  • This is called immediately after image is attached to the DOM and isn't lazy-loaded, etc.
  • Scheduling of the img.decode() callback or the next rAF call, isn't held back by other main thread work.

In other words: this polyfill might suffer from issues that a browser internal implementation might not suffer from.

@noamr
Copy link
Author

noamr commented Apr 23, 2024

correct, it wouldn't be a 100% polyfill, but it demonstrates something very close.

I think conceptually this is useful.

I think there are certain expectations here:

  • This is called immediately after image is attached to the DOM and isn't lazy-loaded, etc.
  • Scheduling of the img.decode() callback or the next rAF call, isn't held back by other main thread work.

In other words: this polyfill might suffer from issues that a browser internal implementation might not suffer from.

correct, it wouldn't be a 100% polyfill, but it demonstrates something very close, and the fact that this polyfill exposes just as much about the image as a browser implementation would.

@noamr
Copy link
Author

noamr commented Apr 24, 2024

Updated a bit and added comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment