问题
I was hoping to get some clarification as it relates to custom elements and their lifecycle callbacks:
I have some confusion with the element created callback. The spec says something like: "called when each instance of an element is created." to my thinking, an instance is inserted into the dom 'virtually' right after it is created, and so the benefit of having these two callback essentially back to back in the document flow. I have also read online that the created callback is more closely related to the element becoming defined. Which of these cases is what the spec says.
This is probably along the lines of the previous question: I see 3 ways of a custom element making it into a document:
It is part of the document from the beginning. In this case, in relation to the document.readyState events, when will the definition be registered?
It is inserted via javascript. I assume that the programmer will register the definition prior to creation and insertion. Then, the question is: when does the created callback fire? When does the attached callback fire? Lastly, if I setup other elements to interact with my element when it is inserted, when can I be sure that that work is finished?
The last method I can think of relates to the shadow dom, and the sense that an element is somewhat half in and half out of the document.
Thank you for reading, I would appreciate any clarification and edification you might be able to provide.
回答1:
I can answer 1 and 2.2 for you.
[Note: this is for the native implementation NOT polymer]
First of all created callback is used in declaration. It is called when you create the element. so when you do
var myElement = document.createElement("custom-element");
The createdCallback is called before the next line of code is called.
When you perform
document.body.appendChild(myElement);
The attachedCallback is called before the next line of code is called.
Now the shadowDom and its css can be a bit more delayed from what I have noticed in my testing of custom elements.
来源:https://stackoverflow.com/questions/29112052/clarification-on-custom-web-components-and-lifecycle-callbacks