wnr / element-resize-detector

Optimized cross-browser resize listener for elements.
MIT License
1.32k stars 118 forks source link

Uncaught TypeError: Cannot read property 'insertBefore' of null #87

Closed marcato15 closed 6 years ago

marcato15 commented 6 years ago

I'm looking to use this plugin in the context of the new Gutenberg editor for Wordpress. However, when I add this plugin I notice that I'm getting the following error:

Uncaught TypeError: Cannot read property 'insertBefore' of null

and the error is coming from the last line of this code.

 function getScrollbarSizes() {
    var width = 500;
    var height = 500;

    var child = document.createElement("div");
    child.style.cssText = "position: absolute; width: " + width*2 + "px; height: " + height*2 + "px; visibility: hidden; margin: 0; padding: 0;";

    var container = document.createElement("div");
    container.style.cssText = "position: absolute; width: " + width + "px; height: " + height + "px; overflow: scroll; visibility: none; top: " + -width*3 + "px; left: " + -height*3 + "px; visibility: hidden; margin: 0; padding: 0;";

    container.appendChild(child);

    document.body.insertBefore(container, document.body.firstChild);

Is it possible to do a check to see if document.body is not null before running the insert? Here's a library that fixed it in a similar fashion https://github.com/christophery/pushy/issues/88

(I may submit a PR tonight or this weekend unless you can see any problem)

wnr commented 6 years ago

Hi,

It is not enough to simply guard against that in order to avoid the error, since the whole system will be in an undefined state in such case (even if no error is thrown). So there needs to be a strategy handling such case, which I'm having a hard time finding a reasonable one. I've rejected numerous "fixes" that simply avoids the actual error throwing, but not solving the "real" issue.

This issue is probably due listenTo being called before the page has loaded (body element is not present). This is something that this library will not handle for you, so you need to make sure that the document is ready yourself. See this thread for some approaches to this. https://stackoverflow.com/questions/9916747/why-is-document-body-null-in-my-javascript

I'm happy to help you solve this, but I don't regard this being an issue with this library so I'll close the issue. Feel free to keep commenting on it though :)