shama / on-load

On load/unload events for DOM elements using a MutationObserver
113 stars 19 forks source link

observe document.documentElement again #39

Closed lukeburns closed 6 years ago

lukeburns commented 6 years ago

https://github.com/shama/on-load/pull/18 was proposed back when when on-load was observing document.body and reverts https://github.com/shama/on-load/pull/34.

https://github.com/shama/on-load/pull/18 forces the user to listen for the DOMContentLoaded event before mutating the DOM if they want to observe those mutations. Before this change, the user could mutate the dom even while document.readyState was loading and observe changes without any trouble. E.g. this breaks the example in morphable which relies on on-load.

Mutating the dom while the document is still loading won't cause problems when we observe document.documentElement, because <html></html> always exists, even if the script is loaded in <head></head>.

This PR goes back to observing document.documentElement. With this change, the following works again as expected.

index.js browserified into bundle.js:

const html = require('nanohtml')
const onload = require('on-load')

document.body = onload(html`<body>hello world</body>`, () => console.log('loaded body'))

index.html:

<html>
  <head>
    <script src="bundle.js"></script>
  </head>
</html>  

Note, that document.documentElement is supported even by old browsers so this approach is also less restrictive.

bcomnes commented 6 years ago

Arg, sorry about that.

bcomnes commented 6 years ago

Once we clarify that point, I'll approve.

lukeburns commented 6 years ago

All good! Without this, I wouldn't have noticed that listening for DOMContentLoaded was unnecessary, and that things would work even if document.body were not present — although, we might want to think about that case more.

bcomnes commented 6 years ago

IIRC on-load would throw if you try to load it in the document head, thats why we wait for body.

bcomnes commented 6 years ago

Are you able to release or do I need to?

lukeburns commented 6 years ago

I expect this to work even when loaded in the head of the document (the example above works properly)

bcomnes commented 6 years ago

Cutting 4.0.1

bcomnes commented 6 years ago

https://github.com/shama/on-load/releases/tag/v4.0.1

lukeburns commented 6 years ago

🙌 thx for your push on this today!