What is the difference between `HTMLImports.whenReady` and `window.addEventListener('WebComponentsReady', function(e) {`

耗尽温柔 提交于 2019-12-10 17:15:31

问题


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

  1. <link rel=import>.onload(),
  2. {HTMLImportsLoaded} event,
  3. HTMLImports.whenReady()
  4. {WebComponentsReady} event

More here.



来源:https://stackoverflow.com/questions/37017594/what-is-the-difference-between-htmlimports-whenready-and-window-addeventliste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!