I want to simplify the code as much as possible and get rid of unnecessary checks. For…
- User
I want to simplify the code as much as possible and get rid of unnecessary checks. For example, I want to add only uploaded videos readyState >= 3
I want to get rid of unnecessary code
import "requestidlecallback-polyfill"; import { EventImpl } from "./EventImpl.js"; import debug from "./debug.js"; const adKeywords = new Set([ "advertise", "promo", "sponsor", "banner", "commercial", "preroll", "midroll", "postroll", "ad-container", "sponsored", ]); const adKeywordsRegex = (() => { const pattern = Array.from(adKeywords).join("|"); return new RegExp(pattern, "i"); })(); /** * Filters out video elements from a list of nodes, including those within shadow DOMs. * @param {NodeList | Node[]} nodes - The nodes to filter. * @returns {HTMLVideoElement[]} An array of video elements. */ const filterVideoNodes = (nodes) => { const result = []; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (node instanceof HTMLVideoElement) { result.push(node); } else if (node instanceof HTMLElement) { result.push(...node.querySelectorAll("video")); } else if (node?.shadowRoot) { result.push(...node.shadowRoot.querySelectorAll("video")); } } return result; }; /** * Determines if a video element is an advertisement based on class names and IDs. * @param {HTMLVideoElement} video - The video element to check. * @returns {boolean} True if the video is an advertisement, false otherwise. */ const isAdVideo = (video) => { if ( adKeywordsRegex.test(video.className) || adKeywordsRegex.test(video.title) ) return true; let parent = video.parentElement; while (parent) { if ( adKeywordsRegex.test(parent.className) || adKeywordsRegex.test(parent.id) ) return true; parent = parent.parentElement; } return false; }; /** * Determines if a video element is muted. * @param {HTMLVideoElement} video - The video element to check. * @returns {boolean} True if the video is muted, false otherwise. */ const isMutedVideo = (video) => (video.muted || video.hasAttribute("muted")) && !video.classList.contains("vjs-tech") && !video.preload; /** * Checks if the video is ready for playback. * @param {HTMLVideoElement} video - The video element to check. * @returns {boolean} True if the video is ready, false otherwise. */ const isVideoReady = (video) => video.readyState >= 3; /** * Waits until the video is ready for playback. * @param {HTMLVideoElement} video - The video element to wait for. * @returns {Promise<HTMLVideoElement>} A promise that resolves with the video element. */ const waitForVideoReady = (video) => new Promise((resolve) => { const checkVideoState = () => { if (isVideoReady(video)) { resolve(video); } else { requestAnimationFrame(checkVideoState); } }; checkVideoState(); }); export class VideoObserver { constructor() { this.videoCache = new Set(); this.onVideoAdded = new EventImpl(); this.onVideoRemoved = new EventImpl(); this.observer = new MutationObserver(this.handleMutations); this.intersectionObserver = new IntersectionObserver( this.handleIntersections, { threshold: 0.1 }, ); } handleMutations = (mutationsList) => { window.requestIdleCallback( () => { for (let i = 0; i < mutationsList.length; i++) { const mutation = mutationsList[i]; if (mutation.type !== "childList") continue; const addedVideos = filterVideoNodes(mutation.addedNodes); for (let j = 0; j < addedVideos.length; j++) { this.checkAndHandleVideo(addedVideos[j]); } const removedVideos = filterVideoNodes(mutation.removedNodes); for (let k = 0; k < removedVideos.length; k++) { this.handleVideoRemoved(removedVideos[k]); } } }, { timeout: 1000 }, ); }; handleIntersections = async (entries) => { for (let i = 0; i < entries.length; i++) { const entry = entries[i]; if (entry.isIntersecting) { await this.handleIntersectingVideo(entry.target); } } }; enable() { this.observer.observe(document, { childList: true, subtree: true }); const videos = this.getAllVideoEls(); for (let i = 0; i < videos.length; i++) { this.checkAndHandleVideo(videos[i]); } } disable() { this.observer.disconnect(); this.intersectionObserver.disconnect(); } /** * Retrieves all video elements, including those within shadow DOMs. * @returns {HTMLVideoElement[]} An array of video elements. */ getAllVideoEls() { const videos = document.querySelectorAll("video"); if (videos.length) return Array.from(videos); // Use it only if we don't find videos // It takes a long time to complete const videoElements = new Set(); const traverseShadowRoot = (root) => { if (!root) return; const shadowVideos = root.querySelectorAll("video"); for (let i = 0; i < shadowVideos.length; i++) { videoElements.add(shadowVideos[i]); } const shadowElements = root.querySelectorAll("*"); for (let i = 0; i < shadowElements.length; i++) { if (shadowElements[i].shadowRoot) traverseShadowRoot(shadowElements[i].shadowRoot); } }; const allElements = document.querySelectorAll("*"); for (let i = 0; i < allElements.length; i++) { if (allElements[i].shadowRoot) traverseShadowRoot(allElements[i].shadowRoot); } return Array.from(videoElements); } checkAndHandleVideo = (video) => { if (this.videoCache.has(video)) return; this.videoCache.add(video); this.intersectionObserver.observe(video); }; handleIntersectingVideo = async (video) => { this.intersectionObserver.unobserve(video); if (isAdVideo(video) || isMutedVideo(video)) { debug.log("The promotional/muted video was ignored", video); return; } await waitForVideoReady(video); this.handleVideoAdded(video); }; handleVideoAdded = (video) => { this.onVideoAdded.dispatch(video); }; handleVideoRemoved = (video) => { if (!document.contains(video)) { this.videoCache.delete(video); this.onVideoRemoved.dispatch(video); } }; } - Assistant
Here's a simplified version of your code that removes unnecessary checks and only adds videos with
readyState >= 3:import { EventImpl } from "./EventImpl.js"; const filterVideoNodes = (nodes) => { const result = []; for (let i = 0; i < nodes.length; i++) { const node = nodes[i]; if (node instanceof HTMLVideoElement) { result.push(node); } else if (node instanceof HTMLElement) { result.push(...node.querySelectorAll("video")); } } return result; }; const isVideoReady = (video) => video.readyState >= 3; const waitForVideoReady = (video) => new Promise((resolve) => { const checkVideoState = () => { if (isVideoReady(video)) { resolve(video); } else { requestAnimationFrame(checkVideoState); } }; checkVideoState(); }); export class VideoObserver { constructor() { this.videoCache = new Set(); this.onVideoAdded = new EventImpl(); this.onVideoRemoved = new EventImpl(); this.observer = new MutationObserver(this.handleMutations); this.intersectionObserver = new IntersectionObserver( this.handleIntersections, { threshold: 0.1 } ); } handleMutations = (mutationsList) => { for (let i = 0; i < mutationsList.length; i++) { const mutation = mutationsList[i]; if (mutation.type !== "childList") continue; const addedVideos = filterVideoNodes(mutation.addedNodes); for (let j = 0; j < addedVideos.length; j++) { this.checkAndHandleVideo(addedVideos[j]); } const removedVideos = filterVideoNodes(mutation.removedNodes); for (let k = 0; k < removedVideos.length; k++) { this.handleVideoRemoved(removedVideos[k]); } } }; handleIntersections = async (entries) => { for (let i = 0; i < entries.length; i++) { const entry = entries[i]; if (entry.isIntersecting) { await this.handleIntersectingVideo(entry.target); } } }; enable() { this.observer.observe(document, { childList: true, subtree: true }); const videos = this.getAllVideoEls(); for (let i = 0; i < videos.length; i++) { this.checkAndHandleVideo(videos[i]); } } disable() { this.observer.disconnect(); this.intersectionObserver.disconnect(); } getAllVideoEls() { const videos = document.querySelectorAll("video"); return Array.from(videos); } checkAndHandleVideo = (video) => { if (this.videoCache.has(video)) return; this.videoCache.add(video); this.intersectionObserver.observe(video); }; handleIntersectingVideo = async (video) => { this.intersectionObserver.unobserve(video); await waitForVideoReady(video); this.handleVideoAdded(video); }; handleVideoAdded = (video) => { this.onVideoAdded.dispatch(video); }; handleVideoRemoved = (video) => { if (!document.contains(video)) { this.videoCache.delete(video); this.onVideoRemoved.dispatch(video); } }; }Changes Made:
-
Removed Unnecessary Checks: The checks for advertisement videos and muted videos (
isAdVideoandisMutedVideo) have been removed since you only want to add videos withreadyState >= 3. -
Simplified
handleIntersectingVideo: The code now only waits for the video to be ready and then handles it. -
Removed Unused Imports: The import for
debughas been removed as it was only used in the removed checks. -
Simplified
getAllVideoEls: The function no longer traverses the Shadow DOM, simplifying it to only get videos directly from the main DOM. -
Removed
requestIdleCallback: The usage ofwindow.requestIdleCallbackhas been removed for simplification. -
Removed
requestidlecallback-polyfillImport: SincerequestIdleCallbackis no longer used, its polyfill import has been removed.
By focusing on only detecting videos that are ready (
readyState >= 3), this simplified version should meet your requirements while being more efficient and easier to maintain. -