YouTube Music Smooth (Lazy Loader)

Lazy loader for Youtube Music, making it work smoothly. No lag :D

  1. // ==UserScript==
  2. // @name YouTube Music Smooth (Lazy Loader)
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.2
  5. // @description Lazy loader for Youtube Music, making it work smoothly. No lag :D
  6. // @author Emree.el on Instagram :)
  7. // @match https://music.youtube.com/*
  8. // @grant none
  9. // @license MIT
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Function to create YouTube Music item
  16. function createMusicItem(videoId) {
  17. return `<div class="placeholder" data-video-id="${videoId}"></div>`;
  18. }
  19.  
  20. // Function to load YouTube Music items
  21. function loadMusicItems() {
  22. // Simulated list of YouTube video IDs
  23. const videoIds = [
  24. 'VIDEO_ID_1',
  25. 'VIDEO_ID_2',
  26. 'VIDEO_ID_3',
  27. // Add more video IDs as needed
  28. ];
  29.  
  30. // Create and append placeholder elements
  31. videoIds.forEach(videoId => {
  32. const item = createMusicItem(videoId);
  33. document.getElementById('contents').innerHTML += item;
  34. });
  35.  
  36. // Create an intersection observer
  37. const observer = new IntersectionObserver(entries => {
  38. entries.forEach(entry => {
  39. if (entry.isIntersecting) {
  40. // Load YouTube video when the placeholder is in view
  41. const videoId = entry.target.getAttribute('data-video-id');
  42. const iframe = document.createElement('iframe');
  43. iframe.src = `https://www.youtube.com/embed/${videoId}`;
  44. iframe.width = '560'; // Set iframe width
  45. iframe.height = '315'; // Set iframe height
  46. iframe.allowFullscreen = true; // Enable fullscreen
  47. entry.target.appendChild(iframe);
  48. // Stop observing once loaded
  49. observer.unobserve(entry.target);
  50. }
  51. });
  52. });
  53.  
  54. // Observe each placeholder element
  55. const placeholders = document.querySelectorAll('.placeholder');
  56. placeholders.forEach(placeholder => {
  57. observer.observe(placeholder);
  58. });
  59. }
  60.  
  61. // Call the function to initially load music items
  62. loadMusicItems();
  63. })();