content-lazy-loader.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global window */
  24. this.singlefile.lib.processors.lazy.content.loader = this.singlefile.lib.processors.lazy.content.loader || (() => {
  25. const ATTRIBUTES_MUTATION_TYPE = "attributes";
  26. const singlefile = this.singlefile;
  27. const browser = this.browser;
  28. const document = window.document;
  29. const MutationObserver = window.MutationObserver;
  30. const addEventListener = (type, listener, options) => window.addEventListener(type, listener, options);
  31. const removeEventListener = (type, listener, options) => window.removeEventListener(type, listener, options);
  32. const timeouts = new Map();
  33. return {
  34. process: async options => {
  35. if (document.documentElement) {
  36. const maxScrollY = Math.max(document.documentElement.scrollHeight - (document.documentElement.clientHeight * 1.5), 0);
  37. const maxScrollX = Math.max(document.documentElement.scrollWidth - (document.documentElement.clientWidth * 1.5), 0);
  38. if (window.scrollY <= maxScrollY && window.scrollX <= maxScrollX) {
  39. return process(options);
  40. }
  41. }
  42. },
  43. resetZoomLevel: options => {
  44. const frames = singlefile.lib.processors.hooks.content.frames;
  45. if (frames) {
  46. frames.loadDeferredImagesResetZoomLevel(options);
  47. }
  48. }
  49. };
  50. function process(options) {
  51. const frames = singlefile.lib.processors.hooks.content.frames;
  52. return new Promise(async resolve => { // eslint-disable-line no-async-promise-executor
  53. let loadingImages;
  54. const pendingImages = new Set();
  55. const observer = new MutationObserver(async mutations => {
  56. mutations = mutations.filter(mutation => mutation.type == ATTRIBUTES_MUTATION_TYPE);
  57. if (mutations.length) {
  58. const updated = mutations.filter(mutation => {
  59. if (mutation.attributeName == "src") {
  60. mutation.target.setAttribute(singlefile.lib.helper.LAZY_SRC_ATTRIBUTE_NAME, mutation.target.src);
  61. mutation.target.addEventListener("load", onResourceLoad);
  62. }
  63. if (mutation.attributeName == "src" || mutation.attributeName == "srcset" || mutation.target.tagName == "SOURCE") {
  64. return !mutation.target.classList || !mutation.target.classList.contains(singlefile.lib.helper.SINGLE_FILE_UI_ELEMENT_CLASS);
  65. }
  66. });
  67. if (updated.length) {
  68. loadingImages = true;
  69. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  70. if (!pendingImages.size) {
  71. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  72. }
  73. }
  74. }
  75. });
  76. await setAsyncTimeout("idleTimeout", () => {
  77. if (!loadingImages) {
  78. clearAsyncTimeout("loadTimeout");
  79. clearAsyncTimeout("maxTimeout");
  80. lazyLoadEnd(observer, options, cleanupAndResolve);
  81. }
  82. }, options.loadDeferredImagesMaxIdleTime * 2);
  83. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  84. observer.observe(document, { subtree: true, childList: true, attributes: true });
  85. if (frames) {
  86. addEventListener(frames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  87. addEventListener(frames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  88. frames.loadDeferredImagesStart(options);
  89. }
  90. function onResourceLoad(event) {
  91. const element = event.target;
  92. element.removeAttribute(singlefile.lib.helper.LAZY_SRC_ATTRIBUTE_NAME);
  93. element.removeEventListener("load", onResourceLoad);
  94. }
  95. async function onImageLoadEvent(event) {
  96. loadingImages = true;
  97. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  98. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  99. if (event.detail) {
  100. pendingImages.add(event.detail);
  101. }
  102. }
  103. async function onImageLoadedEvent(event) {
  104. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  105. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  106. pendingImages.delete(event.detail);
  107. if (!pendingImages.size) {
  108. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  109. }
  110. }
  111. function cleanupAndResolve(value) {
  112. observer.disconnect();
  113. if (frames) {
  114. removeEventListener(frames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  115. removeEventListener(frames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  116. }
  117. resolve(value);
  118. }
  119. });
  120. }
  121. async function deferLazyLoadEnd(observer, options, resolve) {
  122. await setAsyncTimeout("loadTimeout", () => lazyLoadEnd(observer, options, resolve), options.loadDeferredImagesMaxIdleTime);
  123. }
  124. async function deferForceLazyLoadEnd(observer, options, resolve) {
  125. await setAsyncTimeout("maxTimeout", async () => {
  126. await clearAsyncTimeout("loadTimeout");
  127. await lazyLoadEnd(observer, options, resolve);
  128. }, options.loadDeferredImagesMaxIdleTime * 10);
  129. }
  130. async function lazyLoadEnd(observer, options, resolve) {
  131. await clearAsyncTimeout("idleTimeout");
  132. if (singlefile.lib.processors.hooks.content.frames) {
  133. singlefile.lib.processors.hooks.content.frames.loadDeferredImagesEnd(options);
  134. }
  135. await setAsyncTimeout("endTimeout", async () => {
  136. await clearAsyncTimeout("maxTimeout");
  137. resolve();
  138. }, options.loadDeferredImagesMaxIdleTime / 2);
  139. observer.disconnect();
  140. }
  141. async function setAsyncTimeout(type, callback, delay) {
  142. if (browser && browser.runtime && browser.runtime.sendMessage) {
  143. if (!timeouts.get(type)) {
  144. timeouts.set(type, callback);
  145. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.setTimeout", type, delay });
  146. const timeoutCallback = message => {
  147. if (message.method == "singlefile.lazyTimeout.onTimeout" && message.type == type) {
  148. browser.runtime.onMessage.removeListener(timeoutCallback);
  149. callback();
  150. return Promise.resolve({});
  151. }
  152. };
  153. timeouts.delete(type, callback);
  154. browser.runtime.onMessage.addListener(timeoutCallback);
  155. }
  156. } else {
  157. const timeoutId = timeouts.get(type);
  158. if (timeoutId) {
  159. window.clearTimeout(timeoutId);
  160. }
  161. timeouts.set(type, callback);
  162. window.setTimeout(callback, delay);
  163. }
  164. }
  165. async function clearAsyncTimeout(type) {
  166. if (browser && browser.runtime && browser.runtime.sendMessage) {
  167. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.clearTimeout", type });
  168. } else {
  169. const previousTimeoutId = timeouts.get(type);
  170. timeouts.delete(type);
  171. if (previousTimeoutId) {
  172. window.clearTimeout(previousTimeoutId);
  173. }
  174. }
  175. }
  176. })();