javascriptrequirejsbrightcove

Adding Brightcove Video Player Dynamically Using RequireJS


I'm trying to add a brightcove player dynamically by following instructions on this page. Brightcove Player Sample: Loading the Player Dynamically

The video player doesn't initialize when Brightcove's index.min.js is added to the page due to the use of RequireJS.

Here is an example plunk.

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 playurl = "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min.js";

  require([playurl], function() {
      console.log("player script added"); 
  });
}

To see the video player actually working do the following in the index.html file: 1. Comment out the require.js script tag. 2. Remove the comments around the button and playerScript script tag.

Note that the only way the video player works is after the removal of the RequireJS script tag. Does anyone know why this is the case?


Solution

  • The BrightCove site provides an example of using it with RequireJS here.

    Combining this with dynamically loading the player, you might do something like:

    script.js

    var playerData = {
        'accountId': 'xxx',
        'playerId': 'yyy',
        'videoId': 'zzz'
      };
    
    require.config({
      'paths': {
        'bc': "//players.brightcove.net/" + playerData.accountId + "/" + playerData.playerId + "_default/index.min"
      },
      timeout: 30
    });
    
    function addPlayer() {
      // dynamically build the player video element
      var 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
      require(['bc'], function() {
        console.log("player script added");
      });
    }
    
    addPlayer();
    

    index.html

    <!DOCTYPE html>
    <html>
    
    <head>
      <script data-main="script" src="//requirejs.org/docs/release/2.1.20/minified/require.js"></script>
    </head>
    
    <body>
      <div id="placeHolder">Placeholder Here</div>
    </body>
    
    </html>
    

    Here's your plunk updated: http://plnkr.co/edit/vzQQgjnwmRziZJsY6mNH?p=preview