According the MDN documentation on the HTML5 video element, the src
attribute is optional:
src: The URL of the video to embed. This is optional; you may instead use the
<source>
element within the video block to specify the video to embed.
Is there a reason why using the <source>
is any better or worse as an approach? Or is it literally just a different way of doing it?
According the MDN documentation on the HTML5 video element, the src
attribute is optional:
src: The URL of the video to embed. This is optional; you may instead use the
<source>
element within the video block to specify the video to embed.
Is there a reason why using the <source>
is any better or worse as an approach? Or is it literally just a different way of doing it?
3 Answers
Reset to default 4If you want to have different sources you need the source tag to declare them. That's not possible with the src
attribute.
To make it work in all browsers - use
<source>
elements inside the<video>
element.<source>
elements can link to different video files. The browser will use the first recognized format:Sic W3school
You need the source tag if you have more than one source file (you can't have two src
attributes). Usually you should have at least an .mp3
and an .ogg
version of each of your files to ensure patibility with all browsers, so actually, you do need that source tag.
The source
elements allow you to define different formats using only HTML. If the first source can't be read the browser will try the next one and so forth.
With the src
attribute you only got one shot - that is, if used in HTML.
Using JavaScript you can bine the src
property with the canPlayType()
method to determine if a type of format can be played, if result of that call is non-empty then set the src
using the link representing the file for that type. This gives you a more variety of conditional scenarios than you would get from predefined sources in html.