问题
What is the difference between HTMLImports.whenReady
and window.addEventListener('WebComponentsReady', function(e) {
?
Polymer's official documentation says:
"To define an element in your main HTML document, define the element from HTMLImports.whenReady(callback). callback is invoked when all imports in the document have finished loading."
Webcomponents.org's official documentation on imports says:
Under native imports, tags in the main document block the loading of imports. This is to ensure the imports have loaded and any registered elements in them have been upgraded. This native behavior is difficult to polyfill so the HTML Imports polyfill doesn't try. Instead the WebComponentsReady event is a stand in for this behavior:
What is the difference between the two?
回答1:
They are almost * the same: both are triggered at the same time.
So you can choose your favourite flavor between callback
and Event
.
Nota Bene: if, for some reasons, you reference the CustomElement.js
polyfill alone (i.e. without the HTMLImports.js
feature), only the WebComponentsReady
event will be thrown.
(I prefer to use the Event Handler
because in the first case you need to be sure the HTMLImports
is defined, and because it is the only documented API here)
*: Of course they are different! The difference is stated in the quoted definitions.
- The latter is waiting for the Custom Elements to be instanciated. It is triggered by
CustomElement.js
polyfill. - The first is waiting only for the Imports to be loaded and parsed. It is called by
HTMLImports.js
polyfill, just after{HTMLImportsLoaded}
has been sent.
However in normal situation, because Custom Elements are instanciated as soon as they are registered, the 2 events will happen one after the other.
Chronological order
<link rel=import>.onload()
,{HTMLImportsLoaded}
event,HTMLImports.whenReady()
{WebComponentsReady}
event
More here.
来源:https://stackoverflow.com/questions/37017594/what-is-the-difference-between-htmlimports-whenready-and-window-addeventliste