-
Notifications
You must be signed in to change notification settings - Fork 18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
DOM没有ready #23
Comments
放到 DOMContentLoaded 需要等到 DOM加载完成才加载样式,脚本需要尽可能早的加载,否则会出现样式延迟。所有用观察监听。。。 |
是,但是现在document.head返回的不是node,监听就加不上,样式就不会生效呀。 直觉上可能要监听document,然后看add进来的是不是head。 |
这样似乎能解决问题。 --- a/mactype.user.js
+++ b/mactype.user.js
@@ -32,15 +32,17 @@
GM_setValue(name, value);
},
- addStyle(id, tag, css) {
+ addStyle(id, tag, css, node) {
tag = tag || 'style';
let doc = document, styleDom = doc.getElementById(id);
if (styleDom) return;
+ node = node || document.head;
+
let style = doc.createElement(tag);
style.rel = 'stylesheet';
style.id = id;
tag === 'style' ? style.innerHTML = css : style.href = css;
- document.head.appendChild(style);
+ node.appendChild(style);
},
removeElementById(eleId) {
@@ -149,12 +151,20 @@
if (document.head) {
util.addStyle('swal-pub-style', 'style', GM_getResourceText('swalStyle'));
util.addStyle('mactype-style', 'style', style);
+ } else {
+ const headObserver = new MutationObserver((mutationList, observer) => {
+ for (const mutations of mutationList) {
+ for (const node of mutations.addedNodes) {
+ if (node.tagName === 'HEAD') {
+ util.addStyle('swal-pub-style', 'style', GM_getResourceText('swalStyle'), node);
+ util.addStyle('mactype-style', 'style', style, node);
+ observer.disconnect();
+ }
+ }
+ }
+ });
+ headObserver.observe(document, {childList: true, subtree: true});
}
- const headObserver = new MutationObserver(() => {
- util.addStyle('swal-pub-style', 'style', GM_getResourceText('swalStyle'));
- util.addStyle('mactype-style', 'style', style);
- });
- headObserver.observe(document.head, {childList: true, subtree: true});
},
isTopWindow() { |
此问题经常性遇到,特别是豆瓣。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
有些时候脚本执行的时候DOM还没有完全加载,就会出现
把main.init放到DOMContentLoaded里似乎可以解决。
The text was updated successfully, but these errors were encountered: