Sync HTML Import
As suggested by @dandavis, because of the default sync behavior of the <link> and <script> elements, you just need to put your tags in the correct order: registration before calling the method.
Or instead, you can call your own method when the DOMContentLoaded or window.onload event is DOMContentLoaded , as shown below:
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>
Asynchronous HTML Import
If for some reason you want to load your HTML import file asynchronously, you can wait for the link.onload event. At that time, << 22> was already detected inside the import, the user element was registered and created.
<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>
With WebComponents.js polyfill
In this situation, polyfill will not instantiate the created object immediately after loading the import. Instead, you should listen to the WebComponentsReady event:
document.addEventListener( "WebComponentsReady", function () { console.log( "WebComponentsReady" ) var project_list = document.getElementsByTagName( "project-list" )[0] project_list.custom_method( "some_data" ) } )
It works with Firefox, IE 11, and also with Chrome.
Supersharp
source share