On-demand Youtube embedded player

Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background.

当前为 2015-04-24 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name On-demand Youtube embedded player
  3. // @description Hugely improves load speed of pages with lots of embedded Youtube videos by instantly showing clickable and immediately accessible placeholders, then the thumbnails are loaded in background.
  4. // @version 1.0.3
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @grant GM_addStyle
  9. // @grant GM_xmlhttpRequest
  10. // @run-at document-start
  11. // ==/UserScript==
  12.  
  13. var resizeToFit = true;
  14.  
  15. GM_addStyle('\
  16. .instant-youtube-container:not(small) {position:relative; overflow:hidden; cursor:pointer; background-color:black}\
  17. .instant-youtube-container:not(small) .instant-youtube-thumbnail {transition:opacity 0.1s ease-out; opacity:0}\
  18. .instant-youtube-container:not(small) .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px}\
  19. .instant-youtube-container:not(small) .instant-youtube-loading-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; display:block; width:20px; height:20px; background: url("data:image/gif;base64,R0lGODlhFAAUAJEDAMzMzLOzs39/f////yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgADACwAAAAAFAAUAAACPJyPqcuNItyCUJoQBo0ANIxpXOctYHaQpYkiHfM2cUrCNT0nqr4uudsz/IC5na/2Mh4Hu+HR6YBaplRDAQAh+QQFCgADACwEAAIADAAGAAACFpwdcYupC8BwSogR46xWZHl0l8ZYQwEAIfkEBQoAAwAsCAACAAoACgAAAhccMKl2uHxGCCvO+eTNmishcCCYjWEZFgAh+QQFCgADACwMAAQABgAMAAACFxwweaebhl4K4VE6r61DiOd5SfiN5VAAACH5BAUKAAMALAgACAAKAAoAAAIYnD8AeKqcHIwwhGntEWLkO3CcB4biNEIFACH5BAUKAAMALAQADAAMAAYAAAIWnDSpAHa4GHgohCHbGdbipnBdSHphAQAh+QQFCgADACwCAAgACgAKAAACF5w0qXa4fF6KUoVQ75UaA7Bs3yeNYAkWACH5BAUKAAMALAIABAAGAAwAAAIXnCU2iMfaRghqTmMp1moAoHyfIYIkWAAAOw==")}\
  20. .instant-youtube-container:hover:not(small) .ytp-large-play-button-svg {fill:#CC181E}\
  21. .instant-youtube-container:not(small) .instant-youtube-link {\
  22. position: absolute;\
  23. top: 50%;\
  24. color: white;\
  25. display: block;\
  26. left: 0;\
  27. right: 0;\
  28. margin: 40px auto;\
  29. width: 10em;\
  30. height: 1.7em;\
  31. text-align: center;\
  32. text-shadow: 1px 1px 3px black;\
  33. text-decoration: none;\
  34. }\
  35. .instant-youtube-container:not(small) .instant-youtube-link:hover { color:white; text-decoration:underline; background:transparent }\
  36. .instant-youtube-container:not(small) .instant-youtube-embed {position:absolute; left:0; top:0}\
  37. ');
  38.  
  39. processNodes(null, document.querySelectorAll('iframe[src*="youtube.com/embed"]'));
  40. setMutationHandler(document, 'iframe[src*="youtube.com/embed"]', processNodes);
  41.  
  42. function processNodes(observer, nodes) {
  43.  
  44. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  45.  
  46. if (!n.parentNode || n.className.indexOf('instant-youtube-') >= 0 || n.src.indexOf('autoplay=1') > 0)
  47. continue;
  48.  
  49. var id = n.src.match(/embed\/(.+?)(?:[&?\/].*|$)/);
  50. if (!id)
  51. continue;
  52. id = id[1];
  53.  
  54. for (var np=n.parentNode, npw; np && !(npw=np.clientWidth); np=np.parentNode) {}
  55. var containerWidth = resizeToFit ? npw : n.clientWidth;
  56. var containerHeight = resizeToFit ? npw / 16 * 9 : n.clientHeight;
  57.  
  58. var div = document.createElement('div');
  59. div.className = 'instant-youtube-container';
  60. div.srcEmbed = n.src;
  61. div.style.maxWidth = containerWidth + 'px';
  62. div.style.height = containerHeight + 'px';
  63.  
  64. var img = div.appendChild(document.createElement('img'));
  65. img.className = 'instant-youtube-thumbnail';
  66. img.src = 'https://i.ytimg.com/vi' + (window.chrome?'_webp':'') + '/' + id + '/maxresdefault.' + (window.chrome?'webp':'jpg');
  67. if (n.clientHeight) {
  68. img.style.maxWidth = 'auto';
  69. img.style.width = (containerHeight / 9 * 16) + 'px';
  70. img.style.marginLeft = Math.round((containerWidth - containerHeight / 9 * 16) / 2) + 'px';
  71. }
  72. img.title = 'Shift-click to play directly as HTML5 video\n(sometimes buggy: playback starts only after the entire video is loaded)';
  73. img.onload = function(e) {
  74. var img = e.target;
  75. if (img.naturalWidth <= 120)
  76. img.onerror(e);
  77. else {
  78. if (img.src.indexOf('maxresdefault') < 0)
  79. img.style.marginTop = ((img.parentNode.clientHeight - img.clientHeight) / 2).toFixed(1) + 'px';
  80. img.style.setProperty('opacity', '1');
  81. }
  82. }
  83. img.onerror = function(e) {
  84. var img = e.target;
  85. if (img.src.indexOf('maxresdefault') > 0)
  86. img.src = img.src.replace('maxresdefault','hqdefault');
  87. else if (img.src.indexOf('hqdefault.webp') > 0)
  88. img.src = img.src.replace('_webp','').replace('.webp','.jpg');
  89. };
  90.  
  91. div.insertAdjacentHTML('beforeend', '\
  92. <svg class="instant-youtube-play-button"><path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>\
  93. <a class="instant-youtube-link" href="https://www.youtube.com/watch?v=' + id + '">Watch on Youtube</a>\
  94. ');
  95.  
  96. n.parentNode.insertBefore(div, n);
  97. n.remove();
  98.  
  99. div.addEventListener('click', function clickHandler(e) {
  100. if (e.target.localName == 'a')
  101. return;
  102. for (var div = e.target; !div.srcEmbed; div = div.parentNode) {}
  103. var iframeHTML = '<iframe class="instant-youtube-embed" src="' + div.srcEmbed + (div.srcEmbed.indexOf('?') > 0 ? '' : '?') +
  104. '&autoplay=1' +
  105. '&autohide=2' +
  106. '&border=0' +
  107. '&controls=1' +
  108. '&fs=1' +
  109. '&showinfo=1' +
  110. '&ssl=1' +
  111. '&theme=dark' +
  112. '" frameborder="0" allowfullscreen="allowfullscreen" width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>';
  113. div.removeEventListener('click', clickHandler);
  114. div.querySelector('.instant-youtube-play-button').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  115. if (!e.shiftKey)
  116. div.insertAdjacentHTML('beforeend', iframeHTML);
  117. else {
  118. GM_xmlhttpRequest({
  119. method: 'GET',
  120. url: div.srcEmbed.replace('/embed/', '/watch?v='),
  121. onload: function(response) {
  122. var video;
  123. video = div.parentNode.insertBefore(document.createElement('video'), div);
  124. video.controls = true;
  125. video.autoplay = true;
  126. video.width = div.scrollWidth;
  127. video.height = div.scrollHeight;
  128. video.className = 'instant-youtube-container';
  129. var m;
  130. if (m = response.responseText.match(/ytplayer\.config\s*=\s*(\{.+?\});/)) {
  131. var cfg = JSON.parse(m[1]), streams = {};
  132. cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream){
  133. var params = {}
  134. stream.split('&').forEach(function(kv){ params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]) });
  135. streams[params.itag] = params;
  136. });
  137. cfg.args.fmt_list.split(',').forEach(function(fmt){
  138. var itag = fmt.split('/')[0], dimensions = fmt.split('/')[1], stream = streams[itag];
  139. if (stream) {
  140. var source = video.appendChild(document.createElement('source'));
  141. source.src = stream.url;
  142. source.title = stream.quality + ', ' + dimensions + ', ' + stream.type;
  143. }
  144. });
  145. } else {
  146. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  147. var text = response.responseText.split('url_encoded_fmt_stream_map')[1];
  148. while (m = rx.exec(text)) {
  149. video.appendChild(document.createElement('source')).src = decodeURIComponent(decodeURIComponent(m[1]));
  150. }
  151. }
  152. if (video.children.length) {
  153. div.remove();
  154. if (window.chrome) {
  155. video.addEventListener('click', function(e) { if (e.target.paused) {e.target.play()} else {e.target.pause()} });
  156. }
  157. } else {
  158. video.remove();
  159. div.insertAdjacentHTML('beforeend', iframeHTML);
  160. }
  161. }
  162. });
  163. }
  164. });
  165. }
  166. return true;
  167. }
  168.  
  169. function setMutationHandler(baseNode, selector, cb) {
  170. var ob = new MutationObserver(function(mutations){
  171. for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++)
  172. for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++)
  173. if (n.nodeType == 1)
  174. if ((n = n.matches(selector) ? [n] : n.querySelectorAll(selector)) && n.length)
  175. if (!cb(ob, n))
  176. return;
  177. });
  178. ob.observe(baseNode, {subtree:true, childList:true});
  179. }