.init() / .destroy() API

Some website are build in an approach called Single Page Application (abbreviated SPA). this methodology avoids page navigation and page refresh in favor of pseudo navigation using the HTML5 History API or through the older hash portion of the url, without actually navigating away from the page. checkout our PWA guide for more information.

When watching multiple videos without navigating and reloading the page, it's possible that a user will be connected to irrelevant peers and will have lower P2P efficiency. To solve this use case peer5 exposes .init()/.destroy() methods that effectively resets peer5 and allows proper P2P flow on continuous sessions.

Usage

When loading peer5 script its already initiated so there is no need to call init when loading. Whenever the user navigated to another section of the SPA or even when switching to a different video, .init() and .destroy() should be called.

NOTE: it's important to call .destroy() after destroying the player and .init() before creating the new player instance.

1
2
peer5.destroy();
peer5.init();

Example

reacting to page/video change:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function onPageChange(newChannel) {
  // first destroy any existing player
  if (currentPlayer) {
    currentPlayer.destroy();
  }

  // reset peer5
  window.peer5.destroy();
  window.peer5.init();

  // create new player
  currentPlayer = createVideoPlayer(newChannel);
}

React Component Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class VideoChannel extends Component {
  componentWillReceiveProps(newProps) {
    if (newProps.channel && newProps.channel !== this.props.channel) {
        window.peer5.destroy();
        window.peer5.init();
    }
  }

  render() {
    return <VideoPlayer channel={this.props.channel}>
    </VideoPlayer>
  }
}