content-lazy-loader.js 7.2 KB

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