Shadow DOM:是否可以封装JS?

Sas*_*sha 6 html javascript iframe web-component shadow-dom

我试图找到一种方法来封装Javascript而不使用iframe.理想情况下,我想要一种在父页面上加载外部HTML组件(小部件)的方法,而不需要使用iframe来加载两步(首先加载主页,然后才加载iframe内容) ).

是否有可能通过一些新的Web组件技术实现这一点 - 影子DOM /模板/导入?我能够接近将HTML添加到shadow DOM并封装CSS,但无法确认是否可以为组件的javascript执行获取单独的文档.

Ale*_*kin 6

Web-components, being used through HTML imports, encapsulate both Shadow DOM HTML and related script.

To narrow the terminology, let’s consider we have a Polymer component core-ajax. Here is the code. As you might see, it does not provide any HTML markup at all, encapsulating the script only.

Once imported on the host webpage as:

<link 
  rel="import"
  href="https://www.polymer-project.org/components/core-ajax/core-ajax.html"> 
Run Code Online (Sandbox Code Playgroud)

this component provides an ability to perform AJAX calls without any javascript coding:

<core-ajax
  auto
  url="http://gdata.youtube.com/feeds/api/videos/"
  params='{"alt":"json", "q":"chrome"}'
  handleAs="json"
  response='{{response}}'
</core-ajax>
Run Code Online (Sandbox Code Playgroud)

The above will load (since auto attribute is set) the content of the specified URL and put the response into bound response variable. Another way to communicate with this component is to supply handler instead of binding template variable to response:

  - response='{{response}}'
  + on-core-response="{{handleResponse}}"
Run Code Online (Sandbox Code Playgroud)

One might implement handleResponse function in the page’s javascript and that’s it.

UPD Although currently there is no ability to distinguish main document and one used by shadow DOM, this feature is being discussed for almost three years in w3c mailgroups. The discussion is far from conclusion, though, even in aspects like “whether we never entirely enable them in author space.”