Skip to content

Injection fails if the script is run before <head> is parsed #140

@Hash6232

Description

@Hash6232

When bundled in a userscript the injection fails when the script is set to run at document-start instead of document-body or later. Essentially the script ends up running before the DOM has been fully parsed meaning <head> is not there yet causing insertAdjacentElement to fail. This is the tampermonkey documentation.

TypeError: can't access property "insertAdjacentElement", s is undefined

Would it be possible to add a fallback for when there's no <head> yet? Maybe something like:

if (document.head) { injectStyles(); } else { document.addEventListener("DOMContentLoaded", injectStyles); }

or

if (document.head) {
  injectStyles();
} else {
  (function waitForHead() {
    if (document.head) {
      injectStyles();
    } else {
      requestAnimationFrame(waitForHead);
    }
  })();
}

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions