Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does WebComponent adoptedCallback fire?

On MDN documentation, I see a function that WebComponents can implement called adoptedCallback. MDNs documentation states:

"Invoked when the custom element is moved to a new document."

https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_custom_elements

https://github.com/w3c/webcomponents/issues/512

What does it mean that the custom element has moved to a new document? Under what circumstances should I implement this?

like image 306
Nathan Lafferty Avatar asked Jun 22 '18 20:06

Nathan Lafferty


1 Answers

The adoptedCallback() method is called when a Custom Element is moved from one HTML document to another one with the adoptNode() method.

You will meet this use case when you have <iframe> elements in you page: each page will have its own HTML document, the main page and every pages in <iframe> elements.

When you move an element from one frame to another (or to the mail document), its ownerDocument is updated with the new HTMLDocument reference but the element is not destructed and created. That means that the constructor() method will not be called.


You should implement this method only if your custom element will be used in a multi-document context and when you need to perform some special operations that should not be done in connectedCallback(), for example interactions with the owner document, the main document, or other elements.

Example: if you want to display a special interaction when the element is added to the document, but not when is originally inside it, you won't do it in constructor() or in connectedCallback(), but you can do it in adoptedCallback().

adoptedCallback() {
    //change the color to red for 2 seconds
    var slot = this.shadowRoot.querySelector("slot")
    slot.classList.add( "red" )
    setTimeout( () => slot.classList.remove( "red" ), 2000)
}

When you create a custom element, its callbacks are called in this order: constructor > connectedCallback

When you move a custom element whith adoptNode(), the callback are called in this order: disconnectedCallback (with ownerDocument set from source document) > adoptedCallback (with ownerDocument set from new document) > connectedCallback.

When you clone a custom element whith importNode(), the callback are called in that order: constructor > connectedCallback.

Note that connectedCallback() is called when a new custom element is created, but also when it is moved. That's why you should not perform one-time or expensive initializations, like data loading, in the method.


You can deal with multiple documents in other situations, for example when you load HTML documents via HTML Imports.

like image 156
Supersharp Avatar answered Sep 23 '22 02:09

Supersharp