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-10-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.2
  5. // @author wOxxOm
  6. // @namespace wOxxOm.scripts
  7. // @license MIT License
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_addStyle
  11. // @grant GM_xmlhttpRequest
  12. // @run-at document-start
  13. // @require https://greasyfork.org/scripts/12228/code/setMutationHandler.js
  14. // ==/UserScript==
  15.  
  16. var resizeToFit = GM_getValue('resize', true);
  17. var playHTML5 = GM_getValue('playHTML5', false);
  18. var embedSelector = 'iframe[src*="youtube.com/embed"], embed[src*="youtube.com/v"]';
  19.  
  20. processNodes(document.querySelectorAll(embedSelector));
  21. document.addEventListener('DOMContentLoaded', function() {
  22. processNodes(document.querySelectorAll(embedSelector));
  23. setMutationHandler(document, embedSelector, processNodes);
  24. GM_addStyle('\
  25. .instant-youtube-container {position:relative; overflow:hidden; cursor:pointer; background-color:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana;}\
  26. .instant-youtube-container .instant-youtube-thumbnail {transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:0}\
  27. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px}\
  28. .instant-youtube-container .instant-youtube-loading-button {position:absolute; left:0; right:0; top:0; bottom:0; padding: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==")}\
  29. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E}\
  30. .instant-youtube-container .instant-youtube-link, .instant-youtube-container .instant-youtube-link:link, .instant-youtube-container .instant-youtube-link:visited, .instant-youtube-container .instant-youtube-link:active, .instant-youtube-container .instant-youtube-link:focus {\
  31. position:absolute; top:50%; left:0; right:0; width:20em; height:1.7em; margin:60px auto; padding:0; border:none; \
  32. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  33. }\
  34. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px}\
  35. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent}\
  36. .instant-youtube-container .instant-youtube-embed {position:absolute; left:0; top:0; padding:0; margin:0}\
  37. .instant-youtube-container .instant-youtube-link2 {\
  38. display:none; z-index:9; background-color:rgba(0,0,0,0.5); color: white;\
  39. width:100%; height: 1.7em; top:0; left:0; right:0; position:absolute; z-index: 9;\
  40. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  41. margin:0; padding:0.5em 0.5em 0.2em;\
  42. }\
  43. .instant-youtube-container:hover .instant-youtube-link2 {display:block; margin:0}\
  44. .instant-youtube-container .instant-youtube-link2:hover {text-decoration:underline}\
  45. .instant-youtube-container .instant-youtube-link2 b {color:white}\
  46. .instant-youtube-container .instant-youtube-options {position:absolute; right:0; bottom:0; color:white; text-shadow:1px 1px 2px black; padding:0; margin:0 }\
  47. .instant-youtube-container .instant-youtube-options * {font-size:13px; vertical-align:middle; padding:0; margin:0}\
  48. ');
  49. });
  50.  
  51. function processNodes(nodes) {
  52. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  53. if (!n.parentNode || n.className.indexOf('instant-youtube-') >= 0 || n.src.indexOf('autoplay=1') > 0)
  54. continue;
  55.  
  56. var id = n.src.match(/(?:embed\/|v[=\/])(.+?)(?:[&?\/].*|$)/);
  57. if (!id)
  58. continue;
  59. id = id[1];
  60.  
  61. for (var np=n.parentNode, npw; np && !(npw=np.clientWidth); np=np.parentNode) {}
  62. var containerWidth = resizeToFit ? npw : n.clientWidth;
  63. var containerHeight = resizeToFit ? npw / 16 * 9 : n.clientHeight;
  64.  
  65. var div = document.createElement('div');
  66. div.className = 'instant-youtube-container';
  67. div.srcEmbed = n.src;
  68. div.style.maxWidth = containerWidth + 'px';
  69. div.style.height = containerHeight + 'px';
  70. div.originalWidth = n.width;
  71. div.originalHeight = n.height;
  72.  
  73. var img = div.appendChild(document.createElement('img'));
  74. img.className = 'instant-youtube-thumbnail';
  75. img.src = 'https://i.ytimg.com/vi' + (window.chrome?'_webp':'') + '/' + id + '/maxresdefault.' + (window.chrome?'webp':'jpg');
  76. if (n.clientHeight) {
  77. img.style.maxWidth = 'auto';
  78. img.style.width = (containerHeight / 9 * 16) + 'px';
  79. img.style.marginLeft = Math.round((containerWidth - containerHeight / 9 * 16) / 2) + 'px';
  80. }
  81. img.title = 'Shift-click to play directly as HTML5 video';
  82. img.onload = function(e) {
  83. var img = e.target;
  84. if (img.naturalWidth <= 120)
  85. img.onerror(e);
  86. else {
  87. if (img.src.indexOf('maxresdefault') < 0)
  88. img.style.marginTop = ((img.parentNode.clientHeight - img.clientHeight) / 2).toFixed(1) + 'px';
  89. img.style.setProperty('opacity', '1');
  90. }
  91. }
  92. img.onerror = function(e) {
  93. var img = e.target;
  94. if (img.src.indexOf('maxresdefault') > 0)
  95. img.src = img.src.replace('maxresdefault','hqdefault');
  96. else if (img.src.indexOf('hqdefault.webp') > 0)
  97. img.src = img.src.replace('_webp','').replace('.webp','.jpg');
  98. };
  99.  
  100. div.insertAdjacentHTML('beforeend', '\
  101. <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>\
  102. <a class="instant-youtube-link" href="https://www.youtube.com/watch?v=' + id + '" target="_blank">Watch on Youtube</a>\
  103. <span class="instant-youtube-link" style="top:calc(50% + 2em)">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  104. <div class="instant-youtube-options">\
  105. <label for="instant-youtube-options-resize">Resize to fit</label>\
  106. <input type="checkbox" id="instant-youtube-options-resize"' + (resizeToFit ? ' checked' : '') + '>\
  107. <label for="instant-youtube-options-html5" title="Shift-click on thumbnail to switch the mode for that video">Play directly</label>\
  108. <input type="checkbox" id="instant-youtube-options-html5"' + (playHTML5 ? ' checked' : '') + '>\
  109. </div>\
  110. ');
  111.  
  112. n.parentNode.insertBefore(div, n);
  113. n.remove();
  114.  
  115. div.addEventListener('click', function clickHandler(e) {
  116. if (e.target.href)
  117. return;
  118. if (e.target.parentNode.className == 'instant-youtube-options') {
  119. if (e.target.id == 'instant-youtube-options-resize') {
  120. resizeToFit = e.target.checked;
  121. GM_setValue('resize', resizeToFit);
  122. [].forEach.call(document.querySelectorAll('div.instant-youtube-container'), function(n) {
  123. var w = n.originalWidth, h = n.originalHeight, img = n.querySelector('img');
  124. if (resizeToFit) {
  125. for (var np=n.parentNode, npw; np && !(npw=np.clientWidth); np=np.parentNode) {}
  126. w = npw;
  127. h = npw / 16 * 9;
  128. }
  129. n.style.maxWidth = w + 'px';
  130. n.style.height = h + 'px';
  131. img.style.width = (h / 9 * 16) + 'px';
  132. img.style.marginLeft = Math.round((w - h / 9 * 16) / 2) + 'px';
  133. img.style.marginTop = ((h - img.clientHeight) / 2).toFixed(1) + 'px';
  134. n.querySelector('input').checked = resizeToFit;
  135. var video = n.querySelector('video');
  136. if (video) {
  137. video.width = w;
  138. video.height = h;
  139. }
  140. });
  141. } else if (e.target.id == 'instant-youtube-options-html5') {
  142. playHTML5 = e.target.checked;
  143. GM_setValue('playHTML5', playHTML5);
  144. [].forEach.call(document.querySelectorAll('div.instant-youtube-container span.instant-youtube-link'), function(n) {
  145. n.textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  146. });
  147. }
  148. return;
  149. }
  150. for (var div = e.target; !div.srcEmbed; div = div.parentNode) {}
  151. var iframeHTML = '<iframe class="instant-youtube-embed" src="' + div.srcEmbed + (div.srcEmbed.indexOf('?') > 0 ? '' : '?') +
  152. '&autoplay=1' +
  153. '&autohide=2' +
  154. '&border=0' +
  155. '&controls=1' +
  156. '&fs=1' +
  157. '&showinfo=1' +
  158. '&ssl=1' +
  159. '&theme=dark' +
  160. '" frameborder="0" allowfullscreen="allowfullscreen" width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>';
  161. div.removeEventListener('click', clickHandler);
  162. div.querySelector('svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  163. var alternateMode = e.target.className == 'instant-youtube-link' || e.shiftKey;
  164. if (playHTML5 && alternateMode || !playHTML5 && !alternateMode)
  165. div.insertAdjacentHTML('beforeend', iframeHTML);
  166. else {
  167. div.querySelector('span.instant-youtube-link').style.display = 'none';
  168. GM_xmlhttpRequest({
  169. method: 'GET',
  170. url: div.srcEmbed.replace(/\/(embed\/|v[=\/])/, '/watch?v='),
  171. onload: function(response) {
  172. var video;
  173. video = div.appendChild(document.createElement('video'));
  174. video.controls = true;
  175. video.autoplay = true;
  176. video.width = div.clientWidth;
  177. video.height = div.clientHeight;
  178. video.className = 'instant-youtube-embed';
  179. video.volume = GM_getValue('volume', 0.5);
  180. var m;
  181. if (m = response.responseText.match(/ytplayer\.config\s*=\s*(\{.+?\});\s*ytplayer\.load/)) {
  182. var cfg = JSON.parse(m[1]), streams = {};
  183. cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream){
  184. var params = {}
  185. stream.split('&').forEach(function(kv){ params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]) });
  186. streams[params.itag] = params;
  187. });
  188. cfg.args.fmt_list.split(',').forEach(function(fmt){
  189. var itag = fmt.split('/')[0], dimensions = fmt.split('/')[1], stream = streams[itag];
  190. if (stream) {
  191. var source = video.appendChild(document.createElement('source'));
  192. source.src = stream.url;
  193. source.title = stream.quality + ', ' + dimensions + ', ' + stream.type;
  194. }
  195. });
  196. } else {
  197. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  198. var text = response.responseText.split('url_encoded_fmt_stream_map')[1];
  199. while (m = rx.exec(text)) {
  200. video.appendChild(document.createElement('source')).src = decodeURIComponent(decodeURIComponent(m[1]));
  201. }
  202. }
  203. if (video.children.length) {
  204. if (window.chrome) {
  205. video.addEventListener('click', function(e) { if (e.target.paused) {e.target.play()} else {e.target.pause()} });
  206. }
  207. video.interval = (function() {
  208. return setInterval(function() {
  209. if (video.paused)
  210. clearInterval(video.interval);
  211. else
  212. GM_setValue('volume', video.volume);
  213. }, 1000);
  214. })();
  215. var title = response.responseText.match(/<title>(.+?)(?:\s*-\s*YouTube)?<\/title>/);
  216. if (title) {
  217. var a = div.querySelector('.instant-youtube-link');
  218. a.innerHTML = '<b>' + title[1] + '</b> - watch on Youtube';
  219. a.className = 'instant-youtube-link2';
  220. }
  221. div.querySelector('img').style.display = 'none';
  222. } else {
  223. video.remove();
  224. div.insertAdjacentHTML('beforeend', iframeHTML);
  225. }
  226. }
  227. });
  228. }
  229. });
  230. }
  231. return true;
  232. }