[英]How to execute a script when the custom element is upgraded
我已經定義了一個自定義元素,我想僅在自定義元素升級到其注冊類型時才執行腳本。 用例是我必須調用自定義方法。
我的主 html 文件如下所示:
<project-list></project-list>
<script>
var project_list = document.getElementsByTagName("project-list")[0]
project_list.custom_method("some_data");
</script>
自定義元素在 HTML 導入中注冊,如下所示:
<script>
"use strict";
var currentScript = document._currentScript || document.currentScript;
class ProjectList extends HTMLElement {
createdCallback(){
console.log("created");
}
custom_method(data) {
console.log("custom_method() OK");
console.log(data);
this.innerHTML = data;
}
}
document.registerElement("project-list", ProjectList);
</script>
我的問題很簡單:如何確保只有在自定義元素獲得其custom_method
方法后才調用主 html 文件中的腳本?
我正在尋找一個優雅的解決方案。 規范作者會想到的東西。 我不介意對架構進行相當多的更改(例如,如果有必要,可以將 javascript 從主文件移動到另一個自定義元素中)。
同步 HTML 導入
正如@dandavis 所建議的,由於<link>
和<script>
元素的sync
默認行為,您只需要按正確的順序放置標簽:在方法調用之前注冊。
或者,您可以在DOMContentLoaded
或window.onload
事件被觸發時調用您的自定義方法,如下所示:
window.onload = function() { var project_list = document.getElementsByTagName("project-list")[0] project_list.custom_method("some_data") }
<project-list></project-list> <script> "use strict"; var currentScript = document._currentScript || document.currentScript; class ProjectList extends HTMLElement { createdCallback(){ console.log("created"); } custom_method(data) { console.log("custom_method() OK"); console.log(data); this.innerHTML = data; } } document.registerElement("project-list", ProjectList); </script>
異步 HTML 導入
如果由於某些原因您想異步加載 HTML 導入文件,您可以等待link.onload
事件。 此時的| 導入中的<script>
已經執行,自定義元素已注冊並創建。
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link rel="import" href="projectList.html" id="projectList" async>
<script>
projectList.onload = function ()
{
console.log( "import {loaded}" )
var project_list = document.getElementsByTagName( "project-list" )[0]
project_list.custom_method("some_data")
}
</script>
</head>
<body>
<project-list id="pl"></project-list>
<script>
console.warn( "custom_method is " + pl.custom_method ) //undefined
</script>
</body>
</html>
使用 WebComponents.js polyfill
在這種情況下,polyfill 不會在導入加載后立即實例化創建的對象。 相反,您應該監聽WebComponentsReady
事件:
document.addEventListener( "WebComponentsReady", function ()
{
console.log( "WebComponentsReady" )
var project_list = document.getElementsByTagName( "project-list" )[0]
project_list.custom_method( "some_data" )
} )
它適用於 Firefox、IE 11 和 Chrome。
通過自定義元素模塊中的import
加載依賴項。 例如,一個依賴於 Highcharts 的自定義元素模塊(例如something.mjs
):
import '/node_modules/highcharts/highcharts.js'
class Something extends HTMLElement {}
customElements.define('x-something', Something)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.