From eb83f970fa7350ca0d95eae3785bd615701d46e8 Mon Sep 17 00:00:00 2001 From: yakisova41 Date: Sun, 8 Dec 2024 18:38:58 +0900 Subject: [PATCH] Fix head search process --- extension/userscript.user.js | 40 +++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/extension/userscript.user.js b/extension/userscript.user.js index 6b50684..3c1ed24 100644 --- a/extension/userscript.user.js +++ b/extension/userscript.user.js @@ -710,6 +710,25 @@ function replaceManifest(head) { head.prepend(manifestEl); } +/** + * Run a callback in no time when a head element is found. + * @param {*} callback + */ +function headFinder(callback) { + const observer = new MutationObserver((mutations, obs) => { + const head = document.querySelector("head"); + if (head) { + callback(head); + obs.disconnect(); + } + }); + + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }); +} + /** * スクリプトを実行 */ @@ -728,26 +747,15 @@ function main() { if (head !== null && head !== undefined) { headFound(head); } else { - const i = setInterval(() => { - const head = document.head; - if (head !== undefined && head !== null) { - clearInterval(i); - headFound(head); - } + headFinder((head) => { + headFound(head); }); } } else { // extension - const i = setInterval(() => { - const head = document.head; - if (head !== null) { - clearInterval(i); - headFound(head); - - setTimeout(() => { - replaceManifest(head); - }, 100); - } + headFinder((head) => { + headFound(head); + replaceManifest(head); }); } }