content-lazy-loader.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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 setAsyncTimeout("idleTimeout", () => {
  94. if (!loadingImages) {
  95. clearAsyncTimeout("loadTimeout");
  96. clearAsyncTimeout("maxTimeout");
  97. lazyLoadEnd(observer, options, cleanupAndResolve);
  98. }
  99. }, options.loadDeferredImagesMaxIdleTime * 2);
  100. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  101. observer.observe(document, { subtree: true, childList: true, attributes: true });
  102. addEventListener(hooksFrames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  103. addEventListener(hooksFrames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  104. hooksFrames.loadDeferredImagesStart(options);
  105. function onResourceLoad(event) {
  106. const element = event.target;
  107. element.removeAttribute(helper.LAZY_SRC_ATTRIBUTE_NAME);
  108. element.removeEventListener("load", onResourceLoad);
  109. }
  110. async function onImageLoadEvent(event) {
  111. loadingImages = true;
  112. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  113. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  114. if (event.detail) {
  115. pendingImages.add(event.detail);
  116. }
  117. }
  118. async function onImageLoadedEvent(event) {
  119. await deferForceLazyLoadEnd(observer, options, cleanupAndResolve);
  120. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  121. pendingImages.delete(event.detail);
  122. if (!pendingImages.size) {
  123. await deferLazyLoadEnd(observer, options, cleanupAndResolve);
  124. }
  125. }
  126. function cleanupAndResolve(value) {
  127. observer.disconnect();
  128. removeEventListener(hooksFrames.LOAD_IMAGE_EVENT, onImageLoadEvent);
  129. removeEventListener(hooksFrames.IMAGE_LOADED_EVENT, onImageLoadedEvent);
  130. resolve(value);
  131. }
  132. });
  133. }
  134. async function deferLazyLoadEnd(observer, options, resolve) {
  135. await setAsyncTimeout("loadTimeout", () => lazyLoadEnd(observer, options, resolve), options.loadDeferredImagesMaxIdleTime);
  136. }
  137. async function deferForceLazyLoadEnd(observer, options, resolve) {
  138. await setAsyncTimeout("maxTimeout", async () => {
  139. await clearAsyncTimeout("loadTimeout");
  140. await lazyLoadEnd(observer, options, resolve);
  141. }, options.loadDeferredImagesMaxIdleTime * 10);
  142. }
  143. async function lazyLoadEnd(observer, options, resolve) {
  144. await clearAsyncTimeout("idleTimeout");
  145. hooksFrames.loadDeferredImagesEnd(options);
  146. await setAsyncTimeout("endTimeout", async () => {
  147. await clearAsyncTimeout("maxTimeout");
  148. resolve();
  149. }, options.loadDeferredImagesMaxIdleTime / 2);
  150. observer.disconnect();
  151. }
  152. async function setAsyncTimeout(type, callback, delay) {
  153. if (browser && browser.runtime && browser.runtime.sendMessage) {
  154. if (!timeouts.get(type) || !timeouts.get(type).pending) {
  155. const timeoutData = { callback, pending: true };
  156. timeouts.set(type, timeoutData);
  157. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.setTimeout", type, delay });
  158. timeoutData.pending = false;
  159. }
  160. } else {
  161. const timeoutId = timeouts.get(type);
  162. if (timeoutId) {
  163. globalThis.clearTimeout(timeoutId);
  164. }
  165. timeouts.set(type, callback);
  166. globalThis.setTimeout(callback, delay);
  167. }
  168. }
  169. async function clearAsyncTimeout(type) {
  170. if (browser && browser.runtime && browser.runtime.sendMessage) {
  171. await browser.runtime.sendMessage({ method: "singlefile.lazyTimeout.clearTimeout", type });
  172. } else {
  173. const previousTimeoutId = timeouts.get(type);
  174. timeouts.delete(type);
  175. if (previousTimeoutId) {
  176. globalThis.clearTimeout(previousTimeoutId);
  177. }
  178. }
  179. }