connectedCallback vs window.load

时间:2018-06-16 04:52:36

标签: javascript custom-element

如果自定义元素包含在普通HTML正文中,会出现什么事件?

const elem = document.getElementById('test');

window.addEventListener('load', () => {
  elem.innerHTML = 'window.load';
});

class myDiv extends HTMLElement {
  connectedCallback() {
    elem.innerHTML = 'connectedCallback';
  }
}

customElements.define('my-div', myDiv);
<my-div id="test"></my-div>

看起来window.load总是最后一次。

1 个答案:

答案 0 :(得分:0)

正如@ zer00ne所述,一般规则是只要页面上已有所有内容,就会调用windows.onload

如果您动态创建元素,则会在constructor之后调用connectedCallbackwindow.onload函数。

此外,如果您延迟加载任何组件,那么即使您在触发window.onload之前将HTML放在页面中,它们也会在window.onload之后运行。

&#13;
&#13;
    const loaded = msg => () => console.log(msg);

    window.onload = loaded('window.onload');

    class MyEl extends HTMLElement {
      constructor() {
        super();
        loaded('MyEl.constructor')();
      }

      connectedCallback() {
        loaded('MyEl.connectedCallback')();
      }
    }

    customElements.define('my-el', MyEl);

    setTimeout(()=>{
      console.log('About to create element');
      var newEl = document.createElement('my-el');
      console.log('About to add element to body');
      document.body.appendChild(newEl);
    }, 1000);
    setTimeout(()=>{
      console.log('About to create new script tag');
      newEl = document.createElement('script');
      newEl.textContent = `
      class MyEl2 extends HTMLElement {
        constructor() {
          super();
          loaded('MyEl2.constructor')();
        }

        connectedCallback() {
          loaded('MyEl2.connectedCallback')();
        }
      }

      customElements.define('my-el-2', MyEl2);
      `;
      console.log('About to add script element to body');
      document.body.appendChild(newEl);
    }, 2000);
&#13;
    <my-el></my-el>
    <my-el-2></my-el-2>
&#13;
&#13;
&#13;