1. // ==UserScript==
  2. // @name Fast Youtube embedded player
  3. // @description Fast HTML5 direct playback at 720p is used when selected and available. The script also 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.5.2
  5. // @include *
  6. // @exclude https://www.youtube.com/*
  7. // @author wOxxOm
  8. // @namespace wOxxOm.scripts
  9. // @license MIT License
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_addStyle
  13. // @grant GM_xmlhttpRequest
  14. // @connect-src www.youtube.com
  15. // @connect www.youtube.com
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. /* jshint lastsemic:true, multistr:true, laxbreak:true, -W030, -W041, -W084 */
  20.  
  21. var resizeToFit = GM_getValue('resize', true);
  22. var playHTML5 = GM_getValue('playHTML5', false);
  23. var embedSelector = 'iframe[src*="youtube.com/embed"]:not([src*="enablejsapi=1"]), embed[src*="youtube.com/v"]';
  24.  
  25. processEmbeds(document.querySelectorAll(embedSelector));
  26.  
  27. document.addEventListener('DOMContentLoaded', function() {
  28. if (resizeToFit)
  29. adjustNodes();
  30. injectStylesIfNeeded();
  31. });
  32.  
  33. window.addEventListener('resize', function() {
  34. if (resizeToFit)
  35. adjustNodes();
  36. });
  37.  
  38. var mutQueue = [];
  39. new MutationObserver(function(mutations) {
  40. mutQueue.push(mutations);
  41. if (mutations.length < 100)
  42. processQueue();
  43. else
  44. setTimeout(processQueue, 0);
  45. }).observe(document, {subtree:true, childList:true});
  46.  
  47. function processQueue() {
  48. while (mutQueue.length) {
  49. var mutationBatch = mutQueue.shift();
  50. for (var m=0, ml=mutationBatch.length, mutation; (m<ml) && (mutation=mutationBatch[m]); m++) {
  51. for (var n=0, nodes=mutation.addedNodes, nl=nodes.length, node; (n<nl) && (node=nodes[n]); n++) {
  52. if (node.nodeType != 1) // skip non-ELEMENT_NODE
  53. continue;
  54. if (node.localName == 'iframe' || node.localName == 'embed') {
  55. if (node.src.match(/youtube\.com\/(v|embed)/i) && node.src.indexOf('enablejsapi=1') < 0)
  56. processEmbeds([node]);
  57. }
  58. else if (node.children.length) {
  59. var embeds = node.querySelectorAll(embedSelector);
  60. if (embeds.length)
  61. processEmbeds(embeds);
  62. }
  63. }
  64. }
  65. }
  66. }
  67.  
  68. function processEmbeds(nodes) {
  69. for (var i=0, nl=nodes.length, n; i<nl && (n=nodes[i]); i++) {
  70. if (!n.parentNode ||
  71. n.className.indexOf('instant-youtube-') >= 0 ||
  72. n.src.indexOf('autoplay=1') > 0 ||
  73. n.onload && getComputedStyle(n.parentNode).display == 'none' // skip some retarded loaders
  74. )
  75. continue;
  76.  
  77. var id = n.src.match(/(?:embed\/|v[=\/])([^\s,.()\[\]?]+?)(?:[&?\/].*|$)/);
  78. if (!id)
  79. continue;
  80. id = id[1];
  81.  
  82. for (var np=n.parentNode, npw; np && !(npw=np.clientWidth); np=np.parentNode) {}
  83.  
  84. var containerWidth = resizeToFit ? npw : n.clientWidth;
  85. var containerHeight = resizeToFit ? npw / 16 * 9 : n.clientHeight;
  86.  
  87. var div = document.createElement('div');
  88. div.className = 'instant-youtube-container';
  89. div.srcEmbed = n.src;
  90. div.style.maxWidth = containerWidth + 'px';
  91. div.style.height = containerHeight + 'px';
  92. div.originalWidth = n.width;
  93. div.originalHeight = n.height;
  94. div.videoID = id;
  95.  
  96. var wrapper = div.appendChild(document.createElement('div'));
  97. wrapper.className = 'instant-youtube-wrapper';
  98.  
  99. var img = wrapper.appendChild(document.createElement('img'));
  100. img.className = 'instant-youtube-thumbnail';
  101. img.src = 'https://i.ytimg.com/vi/' + id + '/maxresdefault.jpg';
  102. if (n.clientHeight) {
  103. img.style.maxWidth = 'auto';
  104. img.style.width = (containerHeight / 9 * 16) + 'px';
  105. img.style.marginLeft = Math.round((containerWidth - containerHeight / 9 * 16) / 2) + 'px';
  106. }
  107. img.title = 'Shift-click to use alternative player';
  108. img.onload = function(e) {
  109. var img = e.target;
  110. if (img.naturalWidth <= 120)
  111. img.onerror(e);
  112. else {
  113. img.style.marginTop = ((img.parentNode.clientHeight - img.clientHeight) / 2).toFixed(1) + 'px';
  114. img.style.setProperty('opacity', '1');
  115. }
  116. if (img.parentNode.iframeHasLoader)
  117. img.parentNode.parentNode.style.display = '';
  118. };
  119. img.onerror = function(e) {
  120. var img = e.target;
  121. if (img.src.indexOf('maxresdefault') > 0)
  122. img.src = img.src.replace('maxresdefault','hqdefault');
  123. };
  124.  
  125. GM_xmlhttpRequest({
  126. method: 'GET',
  127. url: div.srcEmbed.replace(/\/(embed\/|v[=\/])/, '/watch?v='),
  128. context: div,
  129. onload: parseWatchPage
  130. });
  131.  
  132. var rnd = Math.random().toString().substr(3);
  133. wrapper.insertAdjacentHTML('beforeend', '\
  134. <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>\
  135. <span class="instant-youtube-link">' + (playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)') + '</span>\
  136. <div class="instant-youtube-options">\
  137. <label>Resize to fit <input data-action="resize" type="checkbox"' + (resizeToFit ? ' checked' : '') + '></label>\
  138. <label title="Tip: shift-clicking thumbnails will use alternative player">\
  139. Play directly <input data-action="direct" type="checkbox"' + (playHTML5 ? ' checked' : '') + '></label>\
  140. </div>\
  141. ');
  142.  
  143. if (n.parentNode.localName == 'object')
  144. n = n.parentNode;
  145. n.parentNode.insertBefore(div, n);
  146. n.remove();
  147.  
  148. div.addEventListener('click', clickHandler);
  149. }
  150.  
  151. injectStylesIfNeeded();
  152. return true;
  153. }
  154.  
  155. function adjustNodes() {
  156. var nearest = null, minDistance = window.innerHeight;
  157. var vids = [].slice.call(document.getElementsByClassName('instant-youtube-container'));
  158. vids.forEach(function(n) {
  159. var bounds = n.getBoundingClientRect();
  160. var distance = Math.abs((bounds.bottom + bounds.top)/2 - window.innerHeight/2);
  161. if (distance < minDistance) {
  162. minDistance = distance;
  163. nearest = n;
  164. }
  165. });
  166. var resized = false;
  167. vids.forEach(function(n) {
  168. if (Math.abs(n.parentNode.clientWidth - parseFloat(n.style.maxWidth)) > 2) {
  169. var img = n.getElementsByClassName('instant-youtube-thumbnail')[0];
  170. var npw = n.parentNode.clientWidth;
  171. var nph = npw / 16 * 9;
  172. n.style.maxWidth = img.style.width = npw + 'px';
  173. n.style.height = nph + 'px';
  174. img.style.marginLeft = Math.round((npw - nph / 9 * 16) / 2) + 'px';
  175. img.style.marginTop = ((nph - img.clientHeight) / 2).toFixed(1) + 'px';
  176. resized = true;
  177. }
  178. });
  179. if (resized && nearest)
  180. setTimeout(function() {
  181. nearest.scrollIntoView();
  182. }, 100);
  183. }
  184.  
  185. function parseWatchPage(response) {
  186. var div = response.context;
  187. var m = response.responseText.match(/ytplayer\.config\s*=\s*(\{.+?\});\s*ytplayer\.load/);
  188. var videoInfo = [];
  189. if (m) {
  190. var cfg = JSON.parse(m[1]), streams = {};
  191. cfg.args.url_encoded_fmt_stream_map.split(',').forEach(function(stream) {
  192. var params = {};
  193. stream.split('&').forEach(function(kv) {
  194. params[kv.split('=')[0]] = decodeURIComponent(kv.split('=')[1]);
  195. });
  196. streams[params.itag] = params;
  197. });
  198. cfg.args.fmt_list.split(',').forEach(function(fmt) {
  199. var itag = fmt.split('/')[0];
  200. var dimensions = fmt.split('/')[1];
  201. var stream = streams[itag];
  202. if (stream) {
  203. videoInfo.push({
  204. src: stream.url,
  205. title: stream.quality + ', ' + dimensions + ', ' + stream.type
  206. });
  207. }
  208. });
  209. } else {
  210. var rx = /url=([^=]+?mime%3Dvideo%252F(?:mp4|webm)[^=]+?)(?:,quality|,itag|.u0026)/g;
  211. var text = response.responseText.split('url_encoded_fmt_stream_map')[1];
  212. while (m = rx.exec(text)) {
  213. videoInfo.push({
  214. src: decodeURIComponent(decodeURIComponent(m[1]))
  215. });
  216. }
  217. }
  218.  
  219. var title = response.responseText.match(/<title>(.+?)(?:\s*-\s*YouTube)?<\/title>/);
  220. if (title) {
  221. var duration = response.responseText.match(/<meta itemprop="duration" content="\D*(\d+.*?)S?">/);
  222. var a = div.firstElementChild.appendChild(document.createElement('a'));
  223. a.className = 'instant-youtube-persistent-title';
  224. a.innerHTML = '<strong>' + title[1] + '</strong>' +
  225. (duration ? '<span>' + duration[1].replace(/[HM]/, ':0').replace(/\b0(\d\d)/, '$1') + '</span>' : '');
  226. a.href = 'https://www.youtube.com/watch?v=' + div.videoID;
  227. a.target = '_blank';
  228. ['animation', 'webkitAnimation', 'mozAnimation'].some(function(prop) {
  229. if (prop in a.style) {
  230. a.style[prop] = 'instant-youtube-fadein 1s ease-in';
  231. setTimeout(function() { a.style[prop] = '' }, 1000);
  232. return true;
  233. }
  234. });
  235. }
  236.  
  237. if (videoInfo.length)
  238. div.videoInfo = videoInfo;
  239.  
  240. injectStylesIfNeeded();
  241. }
  242.  
  243. function clickHandler(e) {
  244. if (e.target.href)
  245. return;
  246. if (e.target.closest('.instant-youtube-options'))
  247. return options(e);
  248. div = e.target.closest('.instant-youtube-container');
  249. div.removeEventListener('click', clickHandler);
  250. div.querySelector('svg').outerHTML = '<span class="instant-youtube-loading-button"></span>';
  251.  
  252. var alternateMode = e.shiftKey || e.target.className == 'instant-youtube-link';
  253. if (div.videoInfo && (!!playHTML5 + !!alternateMode == 1))
  254. playDirectly(div);
  255. else
  256. switchToIFrame.call(div);
  257. }
  258.  
  259. function playDirectly(div) {
  260. div.querySelector('.instant-youtube-options').style.display = 'none';
  261. div.querySelector('.instant-youtube-link').style.display = 'none';
  262.  
  263. var video = document.createElement('video');
  264. video.controls = true;
  265. video.autoplay = true;
  266. video.width = div.clientWidth;
  267. video.height = div.clientHeight;
  268. video.className = 'instant-youtube-embed';
  269. video.volume = GM_getValue('volume', 0.5);
  270.  
  271. div.videoInfo.forEach(function(src) {
  272. var srcdom = video.appendChild(document.createElement('source'));
  273. Object.keys(src).forEach(function(k) { srcdom[k] = src[k] });
  274. srcdom.onerror = switchToIFrame.bind(div);
  275. });
  276.  
  277.  
  278. if (window.chrome) {
  279. video.addEventListener('click', function(e) {
  280. this.paused ? this.play() : this.pause();
  281. });
  282. }
  283. video.interval = (function() {
  284. return setInterval(function() {
  285. if (video.volume != GM_setValue('volume', 0.5))
  286. GM_setValue('volume', video.volume);
  287. }, 1000);
  288. })();
  289. var title = div.querySelector('.instant-youtube-persistent-title');
  290. if (title) {
  291. video.onpause = function() { title.removeAttribute('hidden') };
  292. video.onplay = function() { title.setAttribute('hidden', true) };
  293. }
  294. video.onloadeddata = function(e) {
  295. pauseOtherVideos(this);
  296. div.firstElementChild.appendChild(this);
  297. this.style.opacity = 1;
  298. var img = div.querySelector('img');
  299. img.style.transition = 'opacity 1s';
  300. img.style.opacity = 0;
  301. };
  302. }
  303.  
  304. function switchToIFrame(e) {
  305. var div = this;
  306. if (e) console.log('Direct linking failed on %s, switching to IFRAME player', div.srcEmbed);
  307. var iframeHTML = '<iframe class="instant-youtube-embed" allowtransparency="true" src="' +
  308. div.srcEmbed.replace('/v/', '/embed/') +
  309. (div.srcEmbed.indexOf('?') > 0 ? '&' : '?') +
  310. 'html5=1' +
  311. '&autoplay=1' +
  312. '&autohide=2' +
  313. '&border=0' +
  314. '&controls=1' +
  315. '&fs=1' +
  316. '&showinfo=1' +
  317. '&ssl=1' +
  318. '&theme=dark' +
  319. '&enablejsapi=1' +
  320. '" frameborder="0" allowfullscreen width="' + div.clientWidth + '" height="' + div.clientHeight + '"></iframe>';
  321. div.firstElementChild.insertAdjacentHTML('beforeend', iframeHTML);
  322.  
  323. div.firstElementChild.lastElementChild.onload = function() {
  324. pauseOtherVideos(this);
  325. this.style.opacity = 1;
  326.  
  327. var div = this.closest('.instant-youtube-container');
  328. div.setAttribute('iframe', '');
  329. setTimeout(function() {
  330. div.querySelector('img').style.display = 'none';
  331. var title = div.querySelector('.instant-youtube-persistent-title');
  332. if (title)
  333. title.remove();
  334. }, 2000);
  335. };
  336. if (e && e.target) {
  337. var video = e.target.parentNode;
  338. while (video.lastElementChild)
  339. video.lastElementChild.remove();
  340. }
  341. }
  342.  
  343. function pauseOtherVideos(activePlayer) {
  344. [].forEach.call(activePlayer.ownerDocument.getElementsByClassName('instant-youtube-embed'), function(v) {
  345. if (v == activePlayer)
  346. return;
  347. switch (v.localName) {
  348. case 'video':
  349. if (!v.paused)
  350. v.pause();
  351. break;
  352. case 'iframe':
  353. (function() { try { v.contentWindow.postMessage('{"event":"command", "func":"pauseVideo", "args":""}', '*') } catch(e) {} })();
  354. break;
  355. }
  356. });
  357. }
  358.  
  359. function options(e) {
  360. var action = e.target.dataset.action;
  361. if (action == 'resize') {
  362. resizeToFit = e.target.checked;
  363. GM_setValue('resize', resizeToFit);
  364. [].forEach.call(document.querySelectorAll('div.instant-youtube-container'), function(n) {
  365. var w = n.originalWidth, h = n.originalHeight, img = n.querySelector('img');
  366. if (resizeToFit) {
  367. for (var np=n.parentNode, npw; np && !(npw=np.clientWidth); np=np.parentNode) {}
  368. w = npw;
  369. h = npw / 16 * 9;
  370. }
  371. n.style.maxWidth = w + 'px';
  372. n.style.height = h + 'px';
  373. img.style.width = (h / 9 * 16) + 'px';
  374. img.style.marginLeft = Math.round((w - h / 9 * 16) / 2) + 'px';
  375. img.style.marginTop = ((h - img.clientHeight) / 2).toFixed(1) + 'px';
  376. n.querySelector('[data-action="resize"]').checked = resizeToFit;
  377. var video = n.querySelector('video');
  378. if (video) {
  379. video.width = w;
  380. video.height = h;
  381. }
  382. });
  383. } else if (action == 'direct') {
  384. playHTML5 = e.target.checked;
  385. GM_setValue('playHTML5', playHTML5);
  386. [].forEach.call(document.querySelectorAll('div.instant-youtube-container'), function(div) {
  387. div.querySelector('span.instant-youtube-link').textContent = playHTML5 ? 'Play with Youtube player' : 'Play directly (up to 720p)';
  388. div.querySelector('[data-action="direct"]').checked = playHTML5;
  389. });
  390. }
  391. }
  392.  
  393. function injectStylesIfNeeded() {
  394. if (document.head.innerHTML.indexOf('.instant-youtube-container') > 0)
  395. return;
  396. GM_addStyle('\
  397. .instant-youtube-container {contain:strict; position:relative; overflow:hidden; cursor:pointer; background-color:black; padding:0; margin:0; font:normal 14px/1.0 sans-serif,Arial,Helvetica,Verdana;}\
  398. .instant-youtube-container .instant-youtube-thumbnail {transition:opacity 0.1s ease-out; opacity:0; padding:0; margin:0}\
  399. .instant-youtube-container .instant-youtube-play-button {position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; width:85px; height:60px}\
  400. .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==")}\
  401. .instant-youtube-container:hover .ytp-large-play-button-svg {fill:#CC181E}\
  402. .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 {\
  403. position:absolute; top:50%; left:0; right:0; width:20em; height:1.7em; margin:60px auto; padding:0; border:none; \
  404. display:block; text-align:center; text-decoration:none; color:white; text-shadow:1px 1px 3px black; font-weight:bold;\
  405. }\
  406. .instant-youtube-container span.instant-youtube-link {font-weight:normal; font-size:12px}\
  407. .instant-youtube-container .instant-youtube-link:hover {color:white; text-decoration:underline; background:transparent}\
  408. .instant-youtube-container .instant-youtube-embed {position:absolute; left:0; top:0; padding:0; margin:0; height:inherit!important; opacity:0; transition:opacity 2s!important}\
  409. .instant-youtube-container iframe {z-index:10}\
  410. .instant-youtube-container .instant-youtube-persistent-title {\
  411. display:block; z-index:9; background-color:rgba(0,0,0,0.5); color:white;\
  412. width:100%; height: 1.9em; top:0; left:0; right:0; position:absolute; z-index: 9;\
  413. color:white; text-shadow:1px 1px 2px black; text-align:center; text-decoration:none;\
  414. margin:0; padding:0.5em 0.5em 0.2em; border:none;\
  415. }\
  416. .instant-youtube-container .instant-youtube-persistent-title strong:after {content:" - watch on Youtube"; font-weight:normal; margin-right:1ex}\
  417. .instant-youtube-container .instant-youtube-persistent-title span {color:inherit}\
  418. .instant-youtube-container .instant-youtube-persistent-title span:before {content:"("}\
  419. .instant-youtube-container .instant-youtube-persistent-title span:after {content:")"}\
  420. @-webkit-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  421. @-moz-keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  422. @keyframes instant-youtube-fadein { from {opacity:0} to {opacity:1} }\
  423. .instant-youtube-container:not(:hover) .instant-youtube-persistent-title[hidden] {display:none; margin:0}\
  424. .instant-youtube-container .instant-youtube-persistent-title:hover {text-decoration:underline}\
  425. .instant-youtube-container .instant-youtube-persistent-title strong {color:white}\
  426. .instant-youtube-container .instant-youtube-options {position:absolute; right:2px; bottom:0; color:white; text-shadow:1px 1px 2px black; padding:0; margin:0 }\
  427. .instant-youtube-container .instant-youtube-options * {display:inline; color:white; font-size:13px; vertical-align:middle; padding:0; margin:0}\
  428. ');
  429. }