Skip to content Skip to sidebar Skip to footer

Can A Custom Element's `connectedcallback` Be Called More Than Once Before `disconnectedcallback` Is Called?

The spec says: However, note that connectedCallback can be called more than once, so any initialization work that is truly one-time will need a guard to prevent it from running tw

Solution 1:

All depends on what you're doing in the callbacks, and how many attach/detach events you might reasonably expect. If it's really complex, and if your node might be moved around a lot in the DOM, then it's definitely worth considering events versus renders. In other words, event loop considerations. Take the following example:

var square = document.createElement('custom-square');
var one = document.getElementById('one');
var two = document.getElementById('two');
one.appendChild(square);
two.appendChild(square);
one.appendChild(square);
two.appendChild(square);

In this example you would get several connectedCallbacks and several disconnectedCallbacks: one for each appendChild. However all of these back-to-back appendChild calls are all happening in the same cycle of the event loop.

So while you get four separate connectedCallback calls and also three separate disconnectedCallback calls, the node is only rendered once, appended to #two.

This won't always be a concern, but since most modern browsers try to render at 60 FPS, that means you've got less than 17ms per render cycle to do all of your JavaScript, and for the browser to do all of its parsing/flowing/rendering for a given frame.

If it becomes a concern, you could guard against these sorts of things by deferring appropriate work to a requestAnimationFrame callback, and then cancel that rAF if you have future connectedCallback events before the next render event, since you probably only care about the very last one.

Post a Comment for "Can A Custom Element's `connectedcallback` Be Called More Than Once Before `disconnectedcallback` Is Called?"