Every SPA navigation leaves the previous DebugBar instance (and the whole previous page) in memory
Versions: php-debugbar 3.8.0 (the same code is on master), through fruitcake/laravel-debugbar 4.4.4, with Livewire 4 wire:navigate. Chromium.
What happens. With SPA navigation (wire:navigate, and I'd expect Turbo and htmx boosts to behave the same), each new page's HTML carries the debugbar's init script again, and it builds a new PhpDebugBar.DebugBar. The previous instance is never torn down. It keeps listeners on objects that outlive the page:
windowresize(registerResizeHandler,debugbar.js)- the
prefers-color-schememedia querychange(registerMediaListener) documentlisteners for each ofspaNavigationEvents(registerNavigationListener)documentclickinDatasetWidget(widgets.js, "Close panel when clicking outside")
Each listener's closure holds its instance; the instance holds its element (el, panel), and that element is still attached to the page's old <body>. So every navigation keeps the entire previous page alive, with its DOM and everything that page's scripts held, until the tab closes.
Evidence. Navigating between two pages of our app 20 times with wire:navigate, then forcing a garbage collection and reading the heap on the same page each time:
| after 1 visit | 5 | 10 | 20 | |
|---|---|---|---|---|
| toolbar injected | 15 MB | 49 MB | 91 MB | 173 MB |
toolbar not injected (DEBUGBAR_INJECT=false) |
14 MB | 22 MB | 22 MB | 23 MB |
Heap snapshot retainer chains for an old page's element run through those four listeners, for example Window → EventTargetData → resize listener → (bound) DebugBar → el (div.phpdebugbar) → <body> (detached) → …. Removing only the first three, in a local patch, was not enough: the DatasetWidget document click listener then held the page.
A possible fix. Give DebugBar (and any widget that listens on window/document) a destroy() that removes the listeners it added outside its own element, and have the init script call window.PhpDebugBar.instance?.destroy() before it builds the next one (renderDebugbar in JavascriptRenderer). Happy to send a PR along those lines if that's the direction you'd want.
Workaround for anyone hitting it: DEBUGBAR_INJECT=false stops the toolbar and the leak, while requests are still recorded for the open handler and the Artisan commands.
Hi, try #1078
I have added a condition that checks whether an active instance already exists; if it does, it simply attempts to load the data and does not execute renderDebugbar.
I’m not sure if this will fix the issue; it would be helpful if you could test it and leave your feedback on the PR.
if(window.PhpDebugBar.instance) {
loadDebugbarData();
} else if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', renderDebugbar, { once: true });
} else {
renderDebugbar();
}