Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

oncanplay — handling media readiness for playback

The oncanplay attribute contains JavaScript that runs for the canplay event. For audio and video, this signals readiness to start or resume playback, but does not guarantee that the entire resource can play without buffering interruptions.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<audio oncanplay="handler(event)"></audio>
<video oncanplay="handler(event)"></video>

oncanplay is an event handler content attribute for canplay. Its value is JavaScript code; the handler has access to the event object. The attribute is allowed on all HTML elements, but its typical use is responding to readiness of audio and video elements.

The browser fires canplay when media readiness moves from a lower level to HAVE_FUTURE_DATA or higher. Data is then available to continue playback, but not necessarily enough to play the entire resource without buffering. In contrast, canplaythrough indicates an estimated ability to play through to the end without stopping for buffering. canplay alone does not mean playback is already underway.

In HTML, use oncanplay="handler(event)"; in JavaScript, assign a function to media.oncanplay or call media.addEventListener('canplay', handler). The event name does not include the on prefix. The example dispatches a synthetic event: it checks the connection between the attribute and its handler, not actual media readiness.

Examples

<!doctype html>
<meta charset="utf-8">
<title>oncanplay demo</title>
<audio id="media" oncanplay="document.getElementById('result').textContent = event.type"></audio>
<pre id="result">waiting</pre>
<script>
  const media = document.getElementById('media');
  media.dispatchEvent(new Event('canplay'));
</script>

Result

canplay

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources