ソースを参照

refactored code

Gildas 7 年 前
コミット
6aaac746f0
1 ファイル変更16 行追加11 行削除
  1. 16 11
      lib/lazy/content-lazy-loader.js

+ 16 - 11
lib/lazy/content-lazy-loader.js

@@ -25,6 +25,11 @@ this.lazyLoader = this.lazyLoader || (() => {
 	const LAZY_LOADING_TIMEOUT = 1000;
 	const IDLE_LAZY_LOADING_TIMEOUT = 3000;
 	const MAX_LAZY_LOADING_TIMEOUT = 30000;
+	const SCRIPT_TAG_NAME = "script";
+	const MONITORED_ATTRIBUTES = ["src", "srcset"];
+	const ATTRIBUTES_MUTATION_TYPE = "attributes";
+	const SCRIPT_BEFORE_PATH = "lib/lazy/web-lazy-loader-before.js";
+	const SCRIPT_AFTER_PATH = "lib/lazy/web-lazy-loader-after.js";
 
 	return { process };
 
@@ -42,16 +47,13 @@ this.lazyLoader = this.lazyLoader || (() => {
 				lazyLoadEnd(maxTimeoutId, idleTimeoutId, observer, resolve);
 			}, MAX_LAZY_LOADING_TIMEOUT);
 			const observer = new MutationObserver(mutations => {
-				if (mutations.find(mutation => mutation.type == "attributes")) {
+				if (mutations.find(mutation => mutation.type == ATTRIBUTES_MUTATION_TYPE)) {
 					srcAttributeChanged = true;
 					timeoutId = deferLazyLoadEnd(timeoutId, maxTimeoutId, idleTimeoutId, observer, resolve);
 				}
 			});
-			observer.observe(document, { attributeFilter: ["src", "srcset"], subtree: true, childList: true });
-			const scriptBeforeElement = document.createElement("script");
-			scriptBeforeElement.src = browser.runtime.getURL("lib/lazy/web-lazy-loader-before.js");
-			document.body.appendChild(scriptBeforeElement);
-			scriptBeforeElement.onload = () => scriptBeforeElement.remove();
+			observer.observe(document, { attributeFilter: MONITORED_ATTRIBUTES, subtree: true, childList: true });
+			injectScript(SCRIPT_BEFORE_PATH);
 		});
 	}
 
@@ -64,12 +66,15 @@ this.lazyLoader = this.lazyLoader || (() => {
 		timeout.clear(maxTimeoutId);
 		timeout.clear(idleTimeoutId);
 		timeout.set(resolve, LAZY_LOADING_TIMEOUT);
-		const scriptURL = browser.runtime.getURL("lib/lazy/web-lazy-loader-after.js");
-		const scriptAfterElement = document.createElement("script");
-		scriptAfterElement.src = scriptURL;
-		document.body.appendChild(scriptAfterElement);
-		scriptAfterElement.onload = () => scriptAfterElement.remove();
+		injectScript(SCRIPT_AFTER_PATH);
 		observer.disconnect();
 	}
 
+	function injectScript(path) {
+		const scriptElement = document.createElement(SCRIPT_TAG_NAME);
+		scriptElement.src = browser.runtime.getURL(path);
+		document.body.appendChild(scriptElement);
+		scriptElement.onload = () => scriptElement.remove();
+	}
+
 })();