content-lazy-loader.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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, globalThis */
  24. this.singlefile.lib.processors.lazy.content.loader = this.singlefile.lib.processors.lazy.content.loader || (globalThis => {
  25. const ATTRIBUTES_MUTATION_TYPE = "attributes";
  26. const singlefile = this.singlefile;
  27. const browser = globalThis.browser;
  28. const document = globalThis.document;
  29. const MutationObserver = globalThis.MutationObserver;
  30. const addEventListener = (type, listener, options) => globalThis.addEventListener(type, listener, options);
  31. const removeEventListener = (type, listener, options) => globalThis.removeEventListener(type, listener, options);
  32. const timeouts = new Map();
  33. if (browser && browser.runtime && browser.runtime.onMessage && browser.runtime.onMessage.addListener) {
  34. browser.runtime.onMessage.addListener(message => {
  35. if (message.method == "singlefile.lazyTimeout.onTimeout") {
  36. const timeoutData = timeouts.get(message.type);
  37. if (timeoutData) {
  38. timeouts.delete(message.type);
  39. timeoutData.callback();
  40. }
  41. }
  42. });
  43. }
  44. return {
  45. process,
  46. resetZoomLevel
  47. };
  48. async function process(options) {
  49. if (document.documentElement) {
  50. timeouts.clear();
  51. const maxScrollY = Math.max(document.documentElement.scrollHeight - (document.documentElement.clientHeight * 1.5), 0);
  52. const maxScrollX = Math.max(document.documentElement.scrollWidth - (document.documentElement.clientWidth * 1.5), 0);
  53. if (globalThis.scrollY <= maxScrollY && globalThis.scrollX <= maxScrollX) {
  54. return triggerLazyLoading(options);
  55. }
  56. }
  57. }
  58. function resetZoomLevel(options) {
  59. const frames = singlefile.lib.processors.hooks.content.frames;
  60. if (frames) {
  61. frames.loadDeferredImagesResetZoomLevel(options);
  62. }
  63. }
  64. function triggerLazyLoading(options) {
  65. const frames = singlefile.lib.processors.hooks.content.frames;
  66. return new Promise(async resolve => { // eslint-disable-line no-async-promise-executor
  67. let loadingImages;
  68. const pendingImages = new Set();
  69. const observer = new MutationObserver(async mutations => {
  70. mutations = mutations.filter(mutation => mutation.type == ATTRIBUTES_MUTATION_TYPE);
  71. if (mutations.length) {
  72. const updated = mutations.filter(mutation => {
  73. if (mutation.attributeName == "src") {
  74. mutation.target.setAttribute(singlefile.lib.helper.LAZY_SRC_ATTRIBUTE_NAME, mutation.target.src);
  75. mutation.target.addEventListener("load", onResourceLoad);
  76. }
  77. if (mutation.attributeName == "src" || mutation.attributeName == "srcset" || mutation.target.tagName == "SOURCE") {
  78. return !mutation.target.classList || !mutation.target.classList.contains(singlefile.lib.helper.SINGLE_FILE_UI_ELEMENT_CLASS);
  79. }
  80. });
  81. if (updated.length) {
  82. loadingImages = true;
  83. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  84. if (!pendingImages.size) {
  85. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  86. }
  87. }
  88. }
  89. });
  90. await setAsyncTimeout("idleTimeout", () => {
  91. if (!loadingImages) {
  92. clearAsyncTimeout("loadTimeout");
  93. clearAsyncTimeout("maxTimeout");
  94. lazyLoadEnd(observer, options, cleanupAndResolve);
  95. }
  96. }, options.loadDeferredImagesMaxIdleTime * 2);
  97. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  98. observer.observe(document, { subtree: true, childList: true, attributes: true });
  99. if (frames) {
  100. addEventListener(frames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  101. addEventListener(frames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  102. frames.loadDeferredImagesStart(options);
  103. }
  104. function onResourceLoad(event) {
  105. const element = event.target;
  106. element.removeAttribute(singlefile.lib.helper.LAZY_SRC_ATTRIBUTE_NAME);
  107. element.removeEventListener("load", onResourceLoad);
  108. }
  109. async function onImageLoadEvent(event) {
  110. loadingImages = true;
  111. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  112. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  113. if (event.detail) {
  114. pendingImages.add(event.detail);
  115. }
  116. }
  117. async function onImageLoadedEvent(event) {
  118. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  119. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  120. pendingImages.delete(event.detail);
  121. if (!pendingImages.size) {
  122. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  123. }
  124. }
  125. function cleanupAndResolve(value) {
  126. observer.disconnect();
  127. if (frames) {
  128. removeEventListener(frames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  129. removeEventListener(frames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  130. }
  131. resolve(value);
  132. }
  133. });
  134. }
  135. async function deferLazyLoadEnd(observer, options, resolve) {
  136. await setAsyncTimeout("loadTimeout", () => lazyLoadEnd(observer, options, resolve), options.loadDeferredImagesMaxIdleTime);
  137. }
  138. async function deferForceLazyLoadEnd(observer, options, resolve) {
  139. await setAsyncTimeout("maxTimeout", async () => {
  140. await clearAsyncTimeout("loadTimeout");
  141. await lazyLoadEnd(observer, options, resolve);
  142. }, options.loadDeferredImagesMaxIdleTime * 10);
  143. }
  144. async function lazyLoadEnd(observer, options, resolve) {
  145. await clearAsyncTimeout("idleTimeout");
  146. if (singlefile.lib.processors.hooks.content.frames) {
  147. singlefile.lib.processors.hooks.content.frames.loadDeferredImagesEnd(options);
  148. }
  149. await setAsyncTimeout("endTimeout", async () => {
  150. await clearAsyncTimeout("maxTimeout");
  151. resolve();
  152. }, options.loadDeferredImagesMaxIdleTime / 2);
  153. observer.disconnect();
  154. }
  155. async function setAsyncTimeout(type, callback, delay) {
  156. if (browser && browser.runtime && browser.runtime.sendMessage) {
  157. if (!timeouts.get(type) || !timeouts.get(type).pending) {
  158. const timeoutData = { callback, pending: true };
  159. timeouts.set(type, timeoutData);
  160. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.setTimeout", type, delay });
  161. timeoutData.pending = false;
  162. }
  163. } else {
  164. const timeoutId = timeouts.get(type);
  165. if (timeoutId) {
  166. globalThis.clearTimeout(timeoutId);
  167. }
  168. timeouts.set(type, callback);
  169. globalThis.setTimeout(callback, delay);
  170. }
  171. }
  172. async function clearAsyncTimeout(type) {
  173. if (browser && browser.runtime && browser.runtime.sendMessage) {
  174. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.clearTimeout", type });
  175. } else {
  176. const previousTimeoutId = timeouts.get(type);
  177. timeouts.delete(type);
  178. if (previousTimeoutId) {
  179. globalThis.clearTimeout(previousTimeoutId);
  180. }
  181. }
  182. }
  183. })(typeof globalThis == "object" ? globalThis : window);