Click here to see your recently viewed pages and most viewed pages.
Google Developers Academy

Defining an Interface to the Library

Learning objectives
  • Define a JavaScript Object that serves as the library’s namespace and also define an initialization function in that namespace.
  • Validate the initialization parameters.
  • Define an Array in the namespace that will store state information.

A JavaScript library needs a well-defined interface to be used on a web page. The interface should define a namespace and an initialization method within that namespace that takes in parameters.

Define a namespace and initialization function

JavaScript offers a number of different ways to emulate namespaces. The following code shows one way to define the ChapterMarkerPlayer namespace in the global (i.e. window) context and to also define a function, named insert, within that namespace. The insert function takes a single Object parameter, named params, that should specify all of the chapter marker player's options.

// The insert function defined below will insert a new YouTube
// iframe player and chapter markers as a child of an existing HTML
// element on a page.
window.ChapterMarkerPlayer = {
  insert: function(params) {

Validate the initialization parameters

The params object has several required fields. If interface will throw an exception if those fields aren't set to valid values.

// params contains the following required and optional parameter names and values:
//   videoId: (required) The YouTube video id of the video to be embedded.
//   chapters: (required) Mapping of times (seconds since the video's start) to chapter titles.
//   width: (optional) The width of the embedded player. 400px is used by default.
//   playerOptions: (optional) An object corresponding to the options that can be passed to the
//                  YT.Player constructor. See
if (!('videoId' in params)) {
  throw 'The "videoId" parameter must be set to the YouTube video id to be embedded.';

if (!('chapters' in params)) {
  throw 'The "chapters" parameter must be set to the mapping of times to chapter titles.';


var containerElement = document.getElementById(params.container);
if (!containerElement) {
  throw 'The "container" parameter must be set to the id of a existing HTML element.';

Define an array for state information

Additional state information needs to be stored in a globally accessible Array. The Array will be populated and later used by the callback invoked when the iframe Player API has loaded.

// This array keeps track of the callback functions that need to be invoked when the iframe
// API has been loaded.  It avoids a race condition that could occur if multiple
// ChapterMarkerPlayer.insert() calls were made before the API became available.
onYouTubePlayerAPIReadyCallbacks: []

Try it out

View Full Source Code

Live Demo