From 02dff215e79d5d4f475fd4f0c3a1a9564eb29c26 Mon Sep 17 00:00:00 2001 From: mister-ben Date: Mon, 25 Mar 2024 21:53:46 +0100 Subject: [PATCH] perf: Reduce updates --- src/plugin.js | 29 ++++++++++++----------------- src/quality-menu-button.js | 4 +++- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/plugin.js b/src/plugin.js index ec5302b..2ed1dfb 100644 --- a/src/plugin.js +++ b/src/plugin.js @@ -22,24 +22,17 @@ const defaults = { * A Video.js player. * @param {Object} [options={}] * An object of options left to the plugin author to define. - * @return {Function} disposal function for re initialization */ const onPlayerReady = (player, options) => { player.addClass('vjs-quality-menu'); const controlBar = player.getChild('controlBar'); - const button = controlBar.addChild( + controlBar.qualityMenuButton = controlBar.addChild( 'QualityMenuButton', options, controlBar.children_.length - 2 ); - - return function() { - player.removeClass('vjs-quality-menu'); - controlBar.removeChild(button); - button.dispose(); - }; }; /** @@ -50,24 +43,26 @@ const onPlayerReady = (player, options) => { * @param {Object} [options] an object with plugin options */ const initPlugin = function(player, options) { - if (typeof player.qualityLevels !== 'undefined') { + if (player.hasPlugin('qualityLevels')) { // call qualityLevels to initialize it in case it hasnt been initialized yet player.qualityLevels(); - let disposeFn = () => {}; - player.ready(() => { - disposeFn = onPlayerReady(player, options); - - player.on('loadstart', () => { - disposeFn(); - disposeFn = onPlayerReady(player, options); - }); + onPlayerReady(player, options); }); // reinitialization is no-op for now player.qualityMenu = () => {}; player.qualityMenu.VERSION = VERSION; + + player.qualityMenu.dispose = () => { + console.log('disposing plugin'); + player.removeClass('vjs-quality-menu'); + player.controlBar.removeChild(player.controlBar.qualityMenuButton); + player.controlBar.qualityMenuButton.dispose(); + }; + + player.on('dispose', player.qualityMenu.dispose); } }; diff --git a/src/quality-menu-button.js b/src/quality-menu-button.js index 47acfa8..c9e986e 100644 --- a/src/quality-menu-button.js +++ b/src/quality-menu-button.js @@ -66,7 +66,8 @@ class QualityMenuButton extends MenuButton { this.qualityLevels_ = player.qualityLevels(); - this.update = this.update.bind(this); + // Update is debounced because levels are generally added or removed in quick succession + this.update = videojs.fn.debounce(this.update.bind(this), 50); this.handleQualityChange_ = this.handleQualityChange_.bind(this); this.changeHandler_ = () => { @@ -81,6 +82,7 @@ class QualityMenuButton extends MenuButton { this.on(this.qualityLevels_, 'addqualitylevel', this.update); this.on(this.qualityLevels_, 'removequalitylevel', this.update); + this.on(player, 'loadstart', this.update); this.on(this.qualityLevels_, 'change', this.handleQualityChange_); this.one(this.qualityLevels_, 'change', this.changeHandler_);