content-lazy-loader.js 7.7 KB

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