htmx icon indicating copy to clipboard operation
htmx copied to clipboard

parentElement of div not ready when htmx tries to swap it with another element using outerHTML

Open BoPeng opened this issue 3 years ago • 2 comments

I have an application with

<body>
<div id="nav-menu"></div>
<div id="page-content">
</div>
</body>

where the page-content is replaced with another page using hx-get when users navigate through pages through a menu.

I get errors from time to time, saying

image

Tracing into the code I find that, from time to time,

https://github.com/bigskysoftware/htmx/blob/f1cef92e528871993df1a5569b30bb94c99ec847/dist/htmx.js#L620

the <div>'s parentElement, which is the body element, is NULL, causing this error.

What appears to happen is that

  1. A new <div> is replacing #page-content using outerHTML method
  2. The new <div> is rendered, and the user clicks a link, which tries to replace <div> with another <div>.
  3. The old <div> is not yet "hooked" to <body>, causing the error.

One solution that I can think of is to do

<body>
<div id="outer-content">
<div id="page-content">
</div>
</div>
</body>

and the menu would replace #page-content of #outer-content using innerHTML so that outer-content would always exist. I would appreciate if anyone has some better idea though.

BoPeng avatar Feb 02 '22 03:02 BoPeng

Hi @BoPeng ,

Is the error occuring in case of very fast navigation? Like when a developer crazily clicks his application to stress-test it 😇 ? If so, my advice is to setup some production client-side error monitoring, to see how often it happens to your real users. If you're sure that real users are impacted, innerHTML seems the only way to go 😉

David-Guillot avatar Apr 23 '22 17:04 David-Guillot

This happens a lot when I quickly browse around the site since each click will replace a large trunk of the page with a fairly complex one and all the loading and rendering takes time. I have fixed the problem by using innerHTML but thought that htmx could adjust the timing so that the new element will not be displayed before it is "hooked" to its parentElememt.

BoPeng avatar Apr 23 '22 17:04 BoPeng