content-lazy-loader.js 7.6 KB

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