Brightcove Player Sample: Loading the Player Dynamically

The page you are looking for doesn't live here anymore -- redirecting you to in 3 seconds.

In this topic, you will learn how to load the Brightcove player dynamically, that is, on a user event and NOT in the initially written HTML.

Overview

In the working example here you can click the Add Player button to dynamically load the player and play a video.

Three approaches are taken to perform the task:

  • An iframe tag is dynamically built.
  • In-page embed code is dynamically built.
  • The bc() method is used. The bc() method is essential when you need to load the player specific JavaScript before the video element is added to the DOM.

API resources used

  • videojs() method: Creates an instance of the player

The player

Select the Add Player button to dynamically load the player with its associated video. Notice that the video starts playing automatically.

How it works

In the following two sections you will see how to use JavaScript and CSS to dynamically build the standard code used for in-page embed and iframe implementations of Brightcove Player.

It is assumed you have created a Brightcove Player using Studio.

iframe code

The following sections explain the player, JavaScript and CSS code used in the example.

The player code

The player code is simply the code for the iframe implementation displayed when the player is published.

<iframe src='//players.brightcove.net/1752604059001/04ee9f58-9d08-43ea-803f-abda86776db2_default/index.html?videoId=4172255216001'
  allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>

The HTML code

The following HTML is used to target where the dynamically created player will be injected:

  • Lines 23,25: Define the container where the player will by dynamically added.
  • Line 24: Defines the button that when selected adds the player to the page.
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>

The JavaScript code

The JavaScript used will define the variables, create the player code and inject it into the HTML page.

  1. Lines 28-34: Define the variables for the script.
  2. Line 38: The accountId, playerId and videoId fields are used to dynamically create the player code.
  3. Line 41: Dynamically add the player code to your HTML page. The iframe element is built and injected into the HTML page.
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
          'accountId' : '1752604059001',
          'playerId' : '04ee9f58-9d08-43ea-803f-abda86776db2',
          'videoId' : '4172255216001'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<iframe src=\"//players.brightcove.net/' + playerData.accountId + '/' + playerData.playerId + '_default/index.html?videoId=' + playerData.videoId + '\"' + ' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>';

      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
    }
  </script>

The stylesheet

This example uses CSS styles for the Brightcove player.

  • Lines 15-18: Set the dimensions of the iframe element.
  <style>
    iframe {
      width: 640px;
      height: 360px;
    }
  </style>

The complete code

Your page should look similar to this:

<!doctype html>
<html>

<head>
  <meta charset="UTF8">
  <title>Untitled Document</title>
  <style>
    iframe {
      width: 640px;
      height: 360px;
    }
  </style>
</head>

<body>
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>
  <!-- custom script -->
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
          'accountId' : '1752604059001',
          'playerId' : '04ee9f58-9d08-43ea-803f-abda86776db2',
          'videoId' : '4172255216001'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<iframe src=\"//players.brightcove.net/' + playerData.accountId + '/' + playerData.playerId + '_default/index.html?videoId=' + playerData.videoId + '\"' + ' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>';

      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
    }
  </script>
</body>

</html>

iframe code

The following sections explain the player, JavaScript and CSS code used in the example.

The player code

The player code will use a plugin which reads the video type and source URL as query parameters. You could make this implementation much simpler by simply assigning a video to the player in Perform Studio > Players > Video Content section, but the goal in this document is to allow the video content to be set programmatically. In the code below you will see the query parameters videoType and videoURL. These are NOT normal parameters you can use with the iframe implementation, but functional because of the plugin detailed in this section. Note that the values assigned to these parameters must be URL encoded to be part of the URL address.

<iframe src="//players.brightcove.net/3676484087001/68c6e257-366f-482e-926d-5ac004b740a8_default/index.html?videoType=video%2Fmp4&amp;videoURL=http%3A%2F%2Fsolutions.brightcove.com%2Fbcls%2Fassets%2Fvideos%2FTiger.mp4"
  allowfullscreen="" webkitallowfullscreen="" mozallowfullscreen="" kwframeid="1"></iframe>

The HTML code

The following HTML is used to target where the dynamically created player will be injected:

  • Lines 165,167: Define the container where the player will by dynamically added.
  • Line 166: Defines the button that when selected adds the player to the page.
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>

The JavaScript code

The JavaScript used will define the variables, create the player code and inject it into the HTML page. This JavaScript sits in the HTML page in a <script> block.

  1. Lines 171-178: Define the variables for the script. Note that the encodedVideoURL and encodedVideoType variables' values must be in URL encoded format.
  2. Lines 180-186: Define the function called by the button click.
  3. Line 182: The accountId, playerId fields, along with the variables with URL encoded values, are used to dynamically create the player code.
  4. Line 185: Dynamically add the player code to your HTML page. The iframe element is built and injected into the HTML page.
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId' : '3676484087001',
        'playerId' : '68c6e257-366f-482e-926d-5ac004b740a8'
      },
      encodedVideoURL = 'http%3A%2F%2Fsolutions.brightcove.com%2Fbcls%2Fassets%2Fvideos%2FTiger.mp4',
      encodedVideoType = 'video%2Fmp4';

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<iframe src=\"//players.brightcove.net/' + playerData.accountId + '/' + playerData.playerId + '_default/index.html?videoType=' + encodedVideoType + '&videoURL=' + encodedVideoURL + '\"' + ' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>';

      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
    }
  </script>

A player plugin is need to perform the following tasks:

  • Read the query parameters' values from the iframe's URL.
  • Use those values to assign a video to the player.
  • Play the video.
  1. Lines 121,143: Standard code to define a Brightcove Player plugin. In this case the name of the plugin is dynamicLoad.
  2. Lines 135-142: A function that retrieves the value from a URL. The parameter passed to the function is the name of the query parameter for which the value is retrieved.
  3. Line 122: Creates a variable for the player instance.
  4. Lines 123-124: Assigns variables the values of the query parameters using the aforementioned function.
  5. Lines 126-131: Assigns a video source to the player.
  6. Line 133: Plays the video.
videojs.plugin('dynamicLoad', function () {
  var myPlayer = this,
    videoType = getURLparam('videoType'),
    videoURL = getURLparam('videoURL');

  myPlayer.src([
    {
      'type': videoType,
      'src': videoURL
    }
  ]);

  myPlayer.play();

  function getURLparam(name) {
    var regex,
      results;
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }
});

This plugin needs to be associated with the appropriate player using Perform Studio.

The stylesheet

This example uses CSS styles for the Brightcove player.

  • Lines 156-159: Set the dimensions of the iframe element.
  <style>
    iframe {
      width: 640px;
      height: 360px;
    }
  </style>

The complete code

Your page should look similar to this:

<!doctype html>
<html>

<head>
  <meta charset="UTF8">
  <title>Untitled Document</title>
  <style>
    iframe {
      width: 640px;
      height: 360px;
    }
  </style>
</head>

<body>

  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>

  <!-- custom script -->
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId' : '3676484087001',
        'playerId' : '68c6e257-366f-482e-926d-5ac004b740a8'
      },
      encodedVideoURL = 'http%3A%2F%2Fsolutions.brightcove.com%2Fbcls%2Fassets%2Fvideos%2FTiger.mp4',
      encodedVideoType = 'video%2Fmp4';

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<iframe src=\"//players.brightcove.net/' + playerData.accountId + '/' + playerData.playerId + '_default/index.html?videoType=' + encodedVideoType + '&videoURL=' + encodedVideoURL + '\"' + ' allowfullscreen webkitallowfullscreen mozallowfullscreen></iframe>';

      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
    }
  </script>
</body>

</html>

in-page embed code

It is a best practice to use the iframe player implementation as shown above. If you want to get a reference to the player to control it, you can use the in-page embed implementation.

The player code

In this case, you will use the in-page embed implementation displayed when the player is published.

<video
  data-video-id="4172255216001"
  data-account="1752604059001"
  data-player="04ee9f58-9d08-43ea-803f-abda86776db2"
  data-embed="default"
  class="video-js" controls></video>
<script src="//players.brightcove.net/1752604059001/04ee9f58-9d08-43ea-803f-abda86776db2_default/index.min.js"></script>

The JavaScript code

In this JavaScript code you will perform the following tasks:

  • Define the variables.
  • Create the player code.
  • Inject it into the HTML page.
  • Create the appropriate script block and assign the appropriate source.
  • Append the dynamically create script to the page.
  • On the load of the script, which happens automatically with the append, call a function to instantiate the player and play the video.
  1. Lines 84-90: Define the variables for the script. The accountId, playerId and videoId fields are used to dynamically create the player code.
  2. Line 94: Build the video element.
  3. Lines 96: Dynamically add the player code, in this case the video element, to the HTML page.
  4. Lines 98-99: Create the script element, and set its src
  5. Line 100: Adds the script using the appendChild() method, which also runs the script.
  6. Line 101: On the load of the script, call the callback function.
  7. Lines 104-107: In the function, create an instance of the player using the videojs method, and play the video.
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId': '1752604059001',
        'playerId': '04ee9f58-9d08-43ea-803f-abda86776db2',
        'videoId': '3851380732001'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<video id=\"myPlayer\" data-video-id=\"' + playerData.videoId + '\"  data-account=\"' + playerData.accountId + '\" data-player=\"' + playerData.playerId + '\" data-embed=\"default\" class=\"video-js\" controls></video>';
      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
      // add and execute the player script tag
      var s = document.createElement('script');
      s.src = "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min.js";
      document.body.appendChild(s);
      s.onload = callback;
    }

    function callback() {
      myPlayer = videojs('myPlayer');
      myPlayer.play();
    }
  </script>

For this embed version, it will not work with IE 10 and below in fullscreen. This is because fullscreen opens the page in a new window, and the player hasn’t been added to this new page. Use the following to surround the call to the addPlayer() function to correct this issue. The small timeout is necessary as the window name isn’t set immediately.

document.addEventListener('DOMContentLoaded', function () {
  window.setTimeout(function () {
    if (window.name === 'videojs-fullscreen-window') {
      addPlayer();
    }
  }, 10);
}, false);

The complete code

Your page should look similar to this:

<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Load Player Dynamically</title>
  <!-- Page styles -->
  <style>
    .video-js {
      width: 640px;
      height: 360px;
    }
  </style>
</head>

<body>
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>
  <!-- custom script -->
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId': '1752604059001',
        'playerId': '04ee9f58-9d08-43ea-803f-abda86776db2',
        'videoId': '3851380732001'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<video id=\"myPlayer\" data-video-id=\"' + playerData.videoId + '\"  data-account=\"' + playerData.accountId + '\" data-player=\"' + playerData.playerId + '\" data-embed=\"default\" class=\"video-js\" controls></video>';
      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
      // add and execute the player script tag
      var s = document.createElement('script');
      s.src = "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min.js";
      document.body.appendChild(s);
      s.onload = callback;
    }

    function callback() {
      myPlayer = videojs('myPlayer');
      myPlayer.play();
    }
  </script>
</body>

</html>

in-page embed code

It is a best practice to use the iframe player implementation as shown above. If you want to get a reference to the player to control it, you can use the in-page embed implementation.

The player code

In this case, you will use the in-page embed implementation displayed when the player is published.

 <video
  data-account="3676484087001"
  data-player="68c6e257-366f-482e-926d-5ac004b740a8"
  data-embed="default"
  class="video-js" controls></video>
<script src="//players.brightcove.net/3676484087001/68c6e257-366f-482e-926d-5ac004b740a8_default/index.min.js"></script>

The JavaScript code

In this JavaScript code you will perform the following tasks:

  • Define the variables.
  • Create the player code.
  • Inject it into the HTML page.
  • Create the appropriate script block and assign the appropriate source
  • Append the dynamically create script to the page.
  • On the load of the script, which happens automatically with the append, call a function to instantiate the player, set the video source, and play the video.
  1. Lines 229-234: Define the variables for the script. The accountId and playerId fields are used to dynamically create the player code.
  2. Line 238: Build the video element.
  3. Lines 240: Dynamically add the player code, in this case the video element, to the HTML page.
  4. Lines 242-243: Create the script element, and set its src.
  5. Line 244: Adds the script using the appendChild() method, which also runs the script.
  6. Line 245: On the load of the script, call the callback function.
  7. Line 249: In the function, create an instance of the player using the videojs method.
  8. Lines 250-253: In the function, set the source of the video.
  9. Lines 254: In the function, play the video.
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId': '3676484087001',
        'playerId': '68c6e257-366f-482e-926d-5ac004b740a8'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<video id=\"myPlayer\" data-account=\"' + playerData.accountId + '\" data-player=\"' + playerData.playerId + '\" data-embed=\"default\" class=\"video-js\" controls></video>';
      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
      // add and execute the player script tag
      var s = document.createElement('script');
      s.src = "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min.js";
      document.body.appendChild(s);
      s.onload = callback;
    }

    function callback() {
      myPlayer = videojs('myPlayer');
      myPlayer.src({
        "type": "video/mp4",
        "src": "http://solutions.brightcove.com/bcls/assets/videos/Bird_Titmouse.mp4"
      });
      myPlayer.play();
    }
  </script>

For this embed version, it will not work with IE 10 and below in fullscreen. This is because fullscreen opens the page in a new window, and the player hasn’t been added to this new page. Use the following to surround the call to the addPlayer() function to correct this issue. The small timeout is necessary as the window name isn’t set immediately.

document.addEventListener('DOMContentLoaded', function () {
  window.setTimeout(function () {
    if (window.name === 'videojs-fullscreen-window') {
      addPlayer();
    }
  }, 10);
}, false);

The complete code

Your page should look similar to this:

<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Load Player Dynamically</title>
  <!-- Page styles -->
  <style>
    .video-js {
      width: 640px;
      height: 360px;
    }
  </style>
</head>

<body>
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>
  <!-- custom script -->
  <script type="text/JavaScript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId': '3676484087001',
        'playerId': '68c6e257-366f-482e-926d-5ac004b740a8'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<video id=\"myPlayer\" data-account=\"' + playerData.accountId + '\" data-player=\"' + playerData.playerId + '\" data-embed=\"default\" class=\"video-js\" controls></video>';
      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
      // add and execute the player script tag
      var s = document.createElement('script');
      s.src = "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min.js";
      document.body.appendChild(s);
      s.onload = callback;
    }

    function callback() {
      myPlayer = videojs('myPlayer');
      myPlayer.src({
        "type": "video/mp4",
        "src": "http://solutions.brightcove.com/bcls/assets/videos/Bird_Titmouse.mp4"
      });
      myPlayer.play();
    }
  </script>
</body>

</html>

Use the bc() method

There are times where you will want to the use the bc() method to dynamically instantiate the player rather than the method show above. You will want to use the bc() method when you wish to load the player's JavaScript before the video element is loaded into the DOM. If you use the videojs() method NOT in conjunction with bc(), you will get the Video.js player, but without the customizations that are added by Brightcove Player.

To use the bc() method follow this general approach:

  • Load the player's script. That is, the specific index.min.js file for a player.
  • Dynamically build and inject the video object into the page.
  • Use the bc() method.
  • Use the videojs() method.

The code below executes the general steps:

  • Lines 280-282: Creates an insertion point for the player, also displays the button to call the function which dynamically loads the player.
  • Line 284: Loads the JavaScript specific to a Brightcove Player.
  • Lines 286-292: Creates variables for use in the code, specifically data which will be inserted when the video tag is dynamically created.
  • Lines 294,304: Defines the function called on button click.
  • Line 296: Dynamically builds the specific video tag.
  • Line 298: Inject the newly created tag into the DOM.
  • Line 300: Use the bc() method to initialize the Brightcove Player. The method can take either the player ID or the player element itself as an argument.
  • Line 301-303: Use the videojs() method to create a player instance from the Brightcove Player, identified by its ID.
  <div id="placeHolder">
    <button onclick="addPlayer()">Add Player</button>
  </div>

  <script src="//players.brightcove.net/1507807800001/V1YMyzwie_default/index.min.js"></script>
  <script type="text/javascript">
    var myPlayer,
      playerHTML,
      playerData = {
        'accountId': '1507807800001',
        'playerId': 'V1YMyzwie',
        'videoId': '4607746980001'
      };

    function addPlayer() {
      // dynamically build the player video element
      playerHTML = '<video id=\"myPlayerID\" data-video-id=\"' + playerData.videoId + '\"  data-account=\"' + playerData.accountId + '\" data-player=\"' + playerData.playerId + '\" data-embed=\"default\" class=\"video-js\" controls></video>';
      // inject the player code into the DOM
      document.getElementById('placeHolder').innerHTML = playerHTML;
      // instantiate player
      bc(document.getElementById('myPlayerID'));
      videojs('myPlayerID').ready(function(){
        myPlayer = this;
      });
    }
  </script>