Home > other >  Remove Attribute-defined `onload` from `<body>`
Remove Attribute-defined `onload` from `<body>`

Time:11-22

I've been working on this for a few hours and am at the point where I feel like I might be trying to accomplish something unworkable. Any advice or insight is definitely appreciated!

The use case I'm targeting requires interrupting the browser's DOM parsing before it has a chance to draw the <body> element. To accomplish this, I've used this one-liner as the first script called in my <head> element:

document.replaceChild(document.createElement('html'), document.children[0]);

This successfully prevents the browser from calling any subsequent scripts, and the <body> element remains un-rendered. However, if the markup includes an onload attribute on the <body> element, that function or code is still called by the browser.

As the context which intercepts DOM parsing is in <head>, I can't use document.body.removeEventListener() to drop the event listener, because the body element doesn't exist yet. Setting window.onload to null has no effect, and neither does trying to intercept setting of window.onload using Object.defineProperty(window, 'onload', {...}). In each case, the onload function or statements still get called.

To preempt the obvious question as to why I can't just avoid using <body onl oad="...">, the use case is for developer tooling, so I'm trying to create contingency for certain absolute conditions. If it can't be done, it isn't killer to my project, but I'd sure like to know why it can't be done.

Thanks in advance!

CodePudding user response:

You can use Document readystate at the interactive state, and overwrite the onload attribute.

document.onreadystatechange = () => {
   if (document.readyState === 'interactive') 
      window.onload = null;
}

(Added your code from your comment for completeness.)

  • Related