Video optimization in React
Videos are commonly used on the web for various cases.
For instance, in the SVGinWP project, I use videos to provide quick how-to instructions on how to use the web tool.
However, while videos contribute to webpage content, they can also impact performance. Thus, it's important to prepare video files properly.
Multiple Video Sources
Modern browsers support various video formats. Using multiple formats guarantees quicker loading times and broader compatibility.
Thus, I created separate WebM and MP4 files for each video. WebM is for Chrome, while MP4 suits other browsers.
To display videos on a webpage, two HTML elements are needed. These are <video>
and <source>
.
The <video>
element is the main container, while <source>
defines the video file paths. Using this combination optimizes video playback across browsers.
Note, it is possible to use the <video>
element alone:
<video src="add-svg-code.webm" type="video/webm">
<p>Your browser cannot play the provided video file.</p>
</video>
However, this approach is not advised because of browser compatibility concerns.
A better approach includes the <source>
element to support to multiple formats:
<video>
<source src="add-svg-code.webm" type="video/webm">
<source src="add-svg-code.mp4" type="video/mp4">
<p>Your browser cannot play the provided video file.</p>
</video>
In example above, the <source>
tags have a type
attribute to ensure browsers download only compatible files.
Audio Removal
Another optimization technique concerns audio.
Remember to remove the audio track for muted videos, especially when used as background. Doing so reduces the file size.
For insurance, since SVGinWP videos lack voiceovers, I stripped the audio track from each video to make the file size smaller.
Resolution Reduction
Video resolution also matters when talking about optimization.
4K (3840×2160
) is typically too much for web apps. So, in the SVGinWP project, I opted for 720p (1280×720
) resolution in videos.
It is visually pleasing in a dialog window and more compact in size.
Video Poster
Beside video files, the <video>
element may include an image file.
This image becomes the placeholder until the video fully loads. Also, the <video>
element's poster image gives an idea of the video content.
<video poster="add-svg-code-poster.jpg">
<source src="add-svg-code.webm" type="video/webm">
<source src="add-svg-code.mp4" type="video/mp4">
<p>Your browser cannot play the provided video file.</p>
</video>
The <video>
element can use the poster
attribute to display an image.
However, there is a downside. A poster image results in an additional file request. This consumes bandwidth and demands rendering.