[Video.js] How to Use - Playing Videos with JavaScript

Video content serves to enrich the user experience on websites, amplifying the efficacy of information dissemination for a plethora of purposes. Implementing and managing this pivotal video content effectively on the web necessitates diverse strategies. Among these, Video.js emerges as a paramount tool cherished by numerous web developers. In this article, we'll delve into the fundamental principles of Video.js, its intricate functionalities, and juxtapose it with the conventional method of embedding videos via HTML tags.

What is Video.js?

Video.js is a JavaScript and HTML5 library devised to amalgamate and administrate video content on the web.

It's architected to ensure a consistent video playback experience across a myriad of platforms and browsers, aspiring to obviate the need for disparate tools or plugins.

Advantages of Video.js

  1. Cross-Browser Compatibility: Video.js is engineered to function seamlessly across a broad spectrum of web browsers and devices. This ensures users can indulge in video playback without the exigency for auxiliary plugins or tools.
  2. Customizable Aesthetics: Video.js proffers an entirely customizable skin, enabling you to tailor the video player's design consonant with your website's aesthetic and branding.
  3. Plugin Support: Video.js extends support for a diverse array of plugins, facilitating the enhancement or modification of the video player's functionalities.
  4. Open Source: Video.js is an open-source library, flourishing under the assiduous participation and support of the web community and developers.

Drawbacks of Video.js

  1. Learning Curve: Albeit Video.js is lauded for its user-centric design, neophytes might encounter a modicum of a learning curve, especially during initial configurations or plugin integrations.
  2. Size Concerns: Incorporating intricate features and plugins might inadvertently augment the webpage's loading time.

Installing Video.js

Installation via CDN

Utilizing the CDN (Content Delivery Network) simplifies the integration of Video.js into your web pages. Just affix the following code at the end of the <head> and <body> tags in your HTML file.

html
<head>
  <link href="https://vjs.zencdn.net/8.5.2/video-js.css" rel="stylesheet" />
</head>

<body>
  <script src="https://vjs.zencdn.net/8.5.2/video.min.js"></script>
</body>

Installation via npm

By harnessing npm (Node Package Manager), you can facilely install and manage Video.js within your local development environment. Execute the command below in your terminal to incorporate Video.js into your project.

bash
npm install --save-dev video.js

Utilizing Video.js

Embedding Videos in HTML

First and foremost, incorporate the video into your web page. Draft the subsequent code within your HTML file:

html
<video id="my-video" class="video-js" width="640" height="360" controls preload="auto" data-setup='{}'>
    <source src="path/to/yourvideo.mp4" type="video/mp4" />
</video>

This code conjures a video player with dimensions 640x360. Ensure the video's path is designated in the src attribute of the source tag.


Controlling Video.js

To manipulate videos using Video.js, initiate Video.js. Add the following code either within the <script> tag or an independent JS file:

javascript
var player = videojs('my-video');

This initializes a video element bearing the ID my-video as a Video.js player.

Play, Pause, and Volume Adjustments

Harnessing the API furnished by Video.js, you can effortlessly implement functionalities such as playing, pausing, and adjusting the volume of the video.

javascript
let player = videojs('my-video');

// Play the video
player.play();

// Pause the video
player.pause();

// Adjust volume (set to 0.5)
player.volume(0.5);

Incorporating Event Handlers

By appending event handlers to the video player, you can govern interactions with the user.

javascript
player.on('play', function() {
    console.log('The video has commenced playback.');
});

player.on('pause', function() {
    console.log('The video has been temporarily halted.');
});

Configuring Diverse Options with Video.js

Video.js offers an array of robust settings tailored for both users and developers. These configurations can be categorized based on video playback quality, user interface, network performance, and overall user experience.

  1. Regarding Playback Quality: Settings optimized for video and audio quality, such as playback resolution, frame rate, and volume control.
  2. Regarding User Interface: Adjustments related to the player's buttons, toolbar, skin, and other UI elements.
  3. Regarding Network Performance: Configurations tied to streaming methods, buffer settings, and overall network optimization.
  4. Regarding User Experience: Options like autoplay, muting, and preload to enhance and control the viewer's experience.

From these broad categories, we will delve into four particularly significant and commonly used options: controls, autoplay, preload, and muted.

1. controls

The controls option dictates whether the user can interact with the video player's start button. Setting controls to true displays the start button, enabling users to initiate the video. Conversely, when set to false, this button remains hidden. In this scenario, video playback can be triggered only using the autoplay attribute or via the Player API.

javascript
var player = videojs('my-video', {
  controls: true
});

2. autoplay

The autoplay option determines whether the video auto-plays upon webpage load. However, for a more seamless user experience, some browsers might restrict autoplay. Thus, exercising caution is essential.

javascript
var player = videojs('my-video', {
  autoplay: true
});

3. preload

The preload option designates the video's preload method. It can assume one of three values:

  • auto: Loads the essential segments of the video in advance.
  • metadata: Only preloads the video's metadata.
  • none: No preloading is conducted.

This setting can influence the user's data consumption and loading duration.

javascript
var player = videojs('my-video', {
  preload: 'auto'
});

4. muted

The muted setting defines the video's initial mute status. When set to true, the video plays in a muted state.

javascript
var player = videojs('my-video', {
  muted: true
});

By adjusting these options based on user requirements and the website's characteristics, one can ensure an optimal video playback experience.


Precautions When Using Autoplay

Implementing the autoplay option triggers the video to play automatically. However, modern browsers, prioritizing user experience, often place limitations on the autoplay feature. Notably, most browsers block the autoplay of unmuted videos.

A potential solution is using the muted option in tandem with autoplay. This increases the likelihood of the video auto-playing in a muted mode, though it doesn't guarantee automatic playback.

javascript
var player = videojs('my-video', {
  autoplay: true,
  muted: true
});

For further insight on autoplay support, consider referring to Detecting Autoplay Support and Programmatic Autoplay and Success/Failure Detection.


Customizing Video.js Skins and Applying Themes

Video.js offers extensive customization features for its player, allowing developers to tailor its appearance according to the aesthetics of their website or app. By leveraging skins and themes, you can achieve the desired appearance and integrate various themes effortlessly.

Skin Customization

Customizing the skin of the Video.js player can be accomplished via CSS. To modify the default style, simply add styles to the player's CSS class.

For instance, to change the play button's color to red, you can craft the following CSS.

css
.video-js .vjs-play-control {
  color: red;
}

For a more intricate skin customization, tools like the Video.js Skin Designer can be employed. This allows you to modify the skin in real-time and instantly observe the results.

Implementing Video.js Themes

The Videojs Themes library provides a myriad of themes for Video.js. Implementing a default theme from this library is straightforward.

  1. Start by including the CSS file of the desired theme in your project. To apply the "city" theme, load the CSS using:
    html
    <link href="path/to/themes/dist/city/index.css" rel="stylesheet">
  2. Add the theme name to the Video.js player's class:
    html
    <video class="video-js vjs-theme-city"></video>

The chosen theme will now be applied to the player. You can experiment with various themes to identify the one that best suits your needs.


Comparing Video Embedding: HTML Tags vs Video.js

In a previous article, [HTML] Embedding Videos: A Comprehensive Guide to Video Integration, we delved into embedding videos on web pages using HTML tags. While this method is straightforward and effective, leveraging external libraries like Video.js offers a plethora of advanced features. What, then, are the distinctions between these two techniques, and when is each most appropriate? Let's juxtapose their pros and cons and ascertain the optimal choice based on different scenarios.

Embedding Videos with HTML Tags

Advantages

  • Simplicity: The <video> tag alone suffices for seamlessly embedding videos onto web pages.
  • No Dependency on External Libraries: No need to load additional libraries or scripts, ensuring faster loading times.
  • Native Browser Support: Most contemporary web browsers natively support the <video> tag.

Drawbacks

  • Limited Functionality: Beyond basic play/pause operations, customizing or adding functionalities can be challenging.
  • Styling Inconsistencies: Different browsers might render the <video> tag with slight design variations.

Embedding Videos with Video.js

Advantages

  • Advanced Capabilities: Offers features such as playback speed control, subtitle addition, playlist functionalities, and more.
  • Extensive Customization: Tailor the player's design and functionalities as per your preferences.
  • Cross-Browser Compatibility: Video.js is crafted to function seamlessly across various browsers and devices.

Drawbacks

  • Loading Overhead: The need to load an external library might prolong the initial loading time.
  • Learning Curve: While the basic usage is intuitive, harnessing advanced features requires delving into documentation and learning.

Which Method Should You Opt for?

  • For Basic Video Playback: The native <video> tag is ideal. It's quick, straightforward, and sufficient for scenarios without the need for additional features.
  • For Advanced Features and Customization: Video.js shines when there's a demand for diverse options and functionalities. It's especially suited for developing sophisticated video services or advanced web applications.

In web development, effectively employing videos can significantly enhance user engagement and interest. Video.js is a powerful tool designed to cater to this, boasting a wide range of features and extensive customization options. Yet, not every project warrants the use of Video.js. For simple video embedding tasks, the native HTML tag is more than adequate. It's pivotal to consider factors like the project's requirements, development environment, anticipated user experience, and more when determining the best approach. Any technological choice should stem from a profound understanding of its merits and demerits. We hope this article has endowed you with a deeper comprehension of embedding videos using Video.js and the native HTML tag.

© Copyright 2023 CLONE CODING