HTML 导入是否提供任何形式的 Javascript 封装?

Do HTML imports provide any form of Javascript encapsulation?

我刚刚阅读了有关使用 HTML 导入进行组件封装的内容。

<link rel=import href="import.html">

文件 import.html 将包含组件所需的所有内容。

但有一个大问题:import.html 中的 Javascript 函数和变量成为 window 命名空间的一部分,这意味着没有任何封装。
恰好具有同名函数的两个不同组件将发生冲突,并且其中一个函数将被覆盖。

HTML 导入是否提供以前不存在的任何形式的 javascript 封装?


示例:

main.html

<link rel=import href="import1.html">
<link rel=import href="import2.html">

<script>
console.log( moduleFunction() ) ; //`moduleFunction` can be called as if it was defined in the outter document
</script>

import1.html

<script>
function moduleFunction(){
    return 'module1' ;
}
</script>

import2.html

<script>
function moduleFunction(){
    return 'module2' ;
}
</script>

没有。但是,将所有内容包装在一个函数中或拥有一个将所有变量存储在 import.html 中的全局对象都可以。

看来你已经有了答案。

Javascript functions and variables inside import.html become part of the window namespace, which means there's no encapsulation whatsoever. Two different components which happen to have a function with the same name will collide and one of the functions will be overridden.

Do HTML imports provide any form of javascript encapsulation that didn't exist before?

spec 相差不大。

HTML5 Rocks:

Script in the import is executed in the context of the window that contains the importing document. So window.document refers to the main page document.

这是not widely supported

Do HTML imports provide any form of javascript encapsulation that didn't exist before?

不,不是单独使用 rel="import"。如果两个单独的 HTML 文档可能包含 <script> 元素,其中声明的函数分别具有相同的标识符,则由开发人员将适当的逻辑合并到过程中;并决定在 main window.

中使用哪个标识符

<link>可以使用lettry..catch。由于 <link> 元素是阻塞的,参见 link elements block DOM parsing too,我们使用 HTML 中 <link> 的顺序来安排标识符声明的检查。也就是说,moduleFunction 应该总是从 "import1.html" 开始定义,除非要求对声明或未声明的特定变量实施不同的检查顺序

<script>    
  let moduleFunction;    
  try {
    moduleFunction = function moduleFunction() {
        return 'module1';
    }
  } catch (err) {
    console.error("module 1 error", err)
  }      
</script>

<script>
  moduleFunction = moduleFunction || void 0;
  if (!moduleFunction) {
    try {
      moduleFunction = function moduleFunction() {
        return 'module2';
      }
    } catch (err) {
      console.error("module2 error", err)
    }
  }
</script>

plnkrhttp://plnkr.co/edit/lzHkc8pydD7q17ldgnrq?p=preview