content-lazy-loader.js 7.3 KB

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