Reputation: 45500
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 twice.
What does this mean? Is it saying that connectedCallback
can be called more than one time (by the browser engine) before disconnectedCallback
is ever called?
If there is always one connectedCallback
for every disconnectedCallback
, then that statement is rather pointless.
I will obviously clean up whatever I create in connectedCallback
in disconnectedCallback
, thus I will not have things "running twice".
Upvotes: 6
Views: 4755
Reputation: 7474
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 connectedCallback
s and several disconnectedCallback
s: 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.
Upvotes: 4