HTML onloadedmetadata Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onloadedmetadata attribute is an inline event handler for the loadedmetadata event on media elements<audio> and <video>. It runs when the browser has loaded metadata about the file: duration, and for video, width and height. That happens before loadeddata in the media timeline. Use it to show duration labels, size the player, or prepare the UI before frame data arrives. Pass the element to your handler (e.g. handleMetadata(this)) — this is not the media element inside a standalone function unless you bind it.

What You’ll Learn

01

Event handler

Inline JS.

02

loadedmetadata

Duration ready.

03

audio / video

Media only.

04

.duration

Read length.

05

addEventListener

Preferred way.

06

vs loadeddata

Event order.

Purpose of onloadedmetadata Attribute

The primary purpose of onloadedmetadata is to react as soon as the browser knows what the media file is — how long it is, how big the video frame is, and what tracks exist — even before enough data is buffered to paint the first frame. That is ideal for displaying “3:42” next to a progress bar or setting the video element’s aspect ratio.

In the loading sequence, loadstartloadedmetadataloadeddatacanplay. Metadata arrives early, so you can update labels while the rest of the file still downloads.

💡
Pass the media element

Use onloadedmetadata="showDuration(this)" or event.target in addEventListener. A bare function name does not get this as the video unless you assign it that way.

📝 Syntax

Set onloadedmetadata on an audio or video element:

onloadedmetadata.html
<audio controls onloadedmetadata="showDuration(this)">
  <source src="track.mp3" type="audio/mpeg">
</audio>

<video controls onloadedmetadata="handleMetadata(this)">
  <source src="clip.mp4" type="video/mp4">
</video>

Syntax Rules

  • Value is JavaScript executed when the loadedmetadata event fires.
  • Works on <audio> and <video> only.
  • Fires once metadata is parsed — before full frame data is ready.
  • Read element.duration, videoWidth, videoHeight (video).
  • Pass this from inline handler or use event.target in listeners.
  • Modern alternative: media.addEventListener("loadedmetadata", handler).
  • Pair with onerror if metadata cannot be loaded.

💎 Values

The onloadedmetadata attribute accepts a string of JavaScript code:

  • onloadedmetadata="handleMetadata(this)" — Pass the media element.
  • onloadedmetadata="showDuration(event.target)" — If using event in listener style.
  • JavaScript: video.onloadedmetadata = () => { … } — inside, video.duration works.
onloadedmetadata-js.html
player.addEventListener("loadedmetadata", () => {
  const mins = Math.floor(player.duration / 60);
  const secs = Math.floor(player.duration % 60);
  document.getElementById("duration").textContent =
    mins + ":" + String(secs).padStart(2, "0");
});

⚡ Quick Reference

Property / eventAvailable after loadedmetadata?Notes
durationYesSeconds (may be NaN until loaded)
videoWidth / videoHeightYes (video)Intrinsic dimensions
First frame paintedNot yetUse loadeddata
Playback readyMaybe notUse canplay
Handler attributeonloadedmetadataInline on media element

Applicable Elements

TargetSupported?Notes
<audio>YesDuration available
<video>YesDuration + dimensions
<body> / windowNoUse onload
<source> aloneNoListen on parent media element

onloadedmetadata vs onloadeddata vs oncanplay

HandlerWhen it firesTypical use
onloadedmetadataMetadata parsedShow duration, set aspect ratio
onloadeddataFrame data at current timeHide spinner, show frame
oncanplayCan start playbackEnable play button

Examples Gallery

Display duration on metadata load, addEventListener, and format mm:ss labels.

👀 Live Preview

Duration appears when metadata loads:

Duration: waiting for metadata…

Example — Show video duration

Read duration when metadata is ready:

video-onloadedmetadata.html
<video controls onloadedmetadata="handleMetadataLoaded(this)">
  <source src="example.mp4" type="video/mp4">
</video>
<p id="metaOut"></p>

<script>
  function handleMetadataLoaded(media) {
    document.getElementById("metaOut").textContent =
      "Duration: " + media.duration.toFixed(1) + " s";
  }
</script>
Try It Yourself

How It Works

Metadata loads before frame data. media.duration becomes available in the handler.

Dynamic Values with JavaScript

Attach with addEventListener:

dynamic-onloadedmetadata.html
<audio id="dynamicMedia" controls>
  <source src="track.mp3" type="audio/mpeg">
</audio>

<script>
  document.getElementById("dynamicMedia").addEventListener("loadedmetadata", function () {
    document.getElementById("log").textContent =
      "Metadata loaded! Duration: " + this.duration + " s";
  });
</script>
Try It Yourself

How It Works

Register once in script. The callback runs when metadata is parsed — often before the user presses play.

Example — Format duration as mm:ss

Build a friendly time label from duration:

format-duration.html
function formatDuration(seconds) {
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return m + ":" + String(s).padStart(2, "0");
}

audio.addEventListener("loadedmetadata", () => {
  label.textContent = formatDuration(audio.duration);
});
Try It Yourself

How It Works

loadedmetadata is the earliest reliable point to read duration for display.

♿ Accessibility

  • Expose duration to users — Screen reader users benefit from visible duration text.
  • Use native controls — Or build custom controls with ARIA labels and keyboard support.
  • Do not rely on metadata alone — Playback may still buffer; use canplay for play readiness.
  • Captions for video — Add <track kind="captions"> for accessible video.
  • Loading states — Announce when duration becomes available with visible text.

🧠 How onloadedmetadata Works

1

Media URL set

Browser requests file.

loadstart
2

Metadata parsed

Duration, size known.

Parse
3

loadedmetadata fires

onloadedmetadata runs.

Event
=

Duration label

UI adapts to media.

Browser Support

The loadedmetadata event and onloadedmetadata handler are supported wherever HTML5 audio and video are supported.

Media Events · Fully supported

Universal onloadedmetadata support

All major browsers fire loadedmetadata on audio and video elements.

99% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onloadedmetadata attribute 99% supported

Bottom line: Reliable for duration and dimension labels on audio/video in all modern browsers.

💡 Best Practices

✅ Do

  • Pass this or use event.target to read duration
  • Use addEventListener("loadedmetadata", …) in production
  • Check isFinite(media.duration) before displaying
  • Show duration early — metadata loads before frame data
  • Pair with onloadeddata and onerror for full UX

❌ Don’t

  • Assume this is the video in a standalone function without passing it
  • Confuse onloadedmetadata with body onload
  • Attach handlers only to <source> — use parent media element
  • Assume playback is ready — wait for canplay if needed
  • Run heavy work synchronously on every metadata event

Conclusion

The onloadedmetadata attribute runs JavaScript when audio or video metadata is ready — the right moment to show duration, dimensions, and prepare the player UI.

Pass the media element explicitly, prefer addEventListener, and follow with onloadeddata when you need frame data or spinners hidden.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onloadedmetadata

Bookmark these before building media players.

5
Core concepts
🎧 02

.duration

Length in sec.

API
🔄 03

Pass this

Element ref.

Gotcha
🎥 04

video size

Width/height.

Video
05

Then loadeddata

Next event.

Timeline

❓ Frequently Asked Questions

It runs JavaScript when the loadedmetadata event fires — when duration and (for video) dimensions are known on audio or video.
loadedmetadata = info about the file. loadeddata = frame data at the current time is loaded.
Use onloadedmetadata="fn(this)" or event.target. A standalone function called without the element does not receive the video as this.
Yes. duration is available on <audio> after metadata loads.
addEventListener("loadedmetadata", handler) is preferred for production.
Yes in all modern browsers with HTML5 media; Internet Explorer 9+.

Master media metadata events

Practice the onloadedmetadata attribute with duration display examples in the Try It editor.

Try onloadedmetadata demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful