From 5382f2353e693bc8e2682eb045e8bb9930829adc Mon Sep 17 00:00:00 2001 From: Shin'ya Ueoka Date: Wed, 17 Mar 2021 22:50:23 +0900 Subject: Load content scripts on document.body is ready --- src/console/index.tsx | 2 +- src/content/Bootstrap.ts | 27 +++++++++++++++++++++++++++ src/content/index.ts | 34 ++++++++++++++++++++++------------ 3 files changed, 50 insertions(+), 13 deletions(-) create mode 100644 src/content/Bootstrap.ts (limited to 'src') diff --git a/src/console/index.tsx b/src/console/index.tsx index 228625e..f9313a0 100644 --- a/src/console/index.tsx +++ b/src/console/index.tsx @@ -11,7 +11,7 @@ import ReactDOM from "react-dom"; const store = createStore(reducers, applyMiddleware(promise)); -window.addEventListener("load", () => { +window.addEventListener("DOMContentLoaded", () => { const wrapper = document.getElementById("vimvixen-console"); ReactDOM.render( diff --git a/src/content/Bootstrap.ts b/src/content/Bootstrap.ts new file mode 100644 index 0000000..62e1530 --- /dev/null +++ b/src/content/Bootstrap.ts @@ -0,0 +1,27 @@ +type Callback = () => void; + +export default class Bootstrap { + constructor() {} + + isReady(): boolean { + return document.body !== null; + } + + waitForReady(callback: Callback): void { + const observer = new MutationObserver(() => { + if (document.body != null) { + observer.disconnect(); + callback(); + } + }); + + observer.observe(document, { + attributes: false, + attributeOldValue: false, + characterData: false, + characterDataOldValue: false, + childList: true, + subtree: true, + }); + } +} diff --git a/src/content/index.ts b/src/content/index.ts index b575e0d..5252338 100644 --- a/src/content/index.ts +++ b/src/content/index.ts @@ -1,22 +1,32 @@ import "reflect-metadata"; import Application from "./Application"; +import Bootstrap from "./Bootstrap"; import consoleFrameStyle from "./site-style"; import { ConsoleFramePresenterImpl } from "./presenters/ConsoleFramePresenter"; import { container } from "tsyringe"; import "./di"; -if (window.self === window.top) { - new ConsoleFramePresenterImpl().initialize(); -} +const initDom = () => { + if (window.self === window.top) { + new ConsoleFramePresenterImpl().initialize(); + } -try { - const app = container.resolve(Application); - app.run(); -} catch (e) { - console.error(e); -} + try { + const app = container.resolve(Application); + app.run(); + } catch (e) { + console.error(e); + } -const style = window.document.createElement("style"); -style.textContent = consoleFrameStyle; -window.document.head.appendChild(style); + const style = window.document.createElement("style"); + style.textContent = consoleFrameStyle; + window.document.head.appendChild(style); +}; + +const bootstrap = new Bootstrap(); +if (bootstrap.isReady()) { + initDom(); +} else { + bootstrap.waitForReady(() => initDom()); +} -- cgit v1.2.3