widget-core icon indicating copy to clipboard operation
widget-core copied to clipboard

Script elements affect custom element initialization

Open jason0x43 opened this issue 7 years ago • 2 comments

Bug

The presence of script elements in a document affects how custom elements are initialized.

What appears to be happening is that the presence of a script element with content (code or just whitespace), the custom element's initialization method is called at the point that the script element is processed in the DOM. So if the script element is before the dojo-button element in the DOM, initialization is called before dojo-button has been processed, so the node is empty (document.body.childNodes at this point contains only a whitespace text node and the script node). If the script element is after dojo-button, the button's content is available in initialization. However, if additional nodes are added to the document after the script element it can be seen that processing is still affected by the presence of the script tag, as document.body.childNodes will only contain nodes up to the script node.

Package Version: 0.3.0

Code

// createButtonElement.ts
export default function createButtonElement(): CustomElementDescriptor {
    return {
        tagName: 'dojo-button',
        widgetConstructor: Button,
        attributes: [],
        properties: [],
        events: [],
        initialization(properties: any) {
            const element = <HTMLElement>(<any>this);
            console.log('element: ' + element.innerHTML);
            properties.label = element.innerHTML;
            element.innerHTML = '';
        }
    };
}
<body>
    <script> </script>
    <dojo-button>Click me</dojo-button>
</body>

Expected behavior:

element.innerHTML should equal "Click me".

Actual behavior:

element.innerHTML is empty.

jason0x43 avatar Dec 15 '17 15:12 jason0x43

Additional information:

This is fine:

<head>
    <script>
    </script>
    <link rel="import href="button/button.html">
</head>
<body>
    <dojo-button>Click me</dojo-button>
</body>

but this is not

<head>
    <link rel="import href="button/button.html">
    <script>
    </script>
</head>
<body>
    <dojo-button>Click me</dojo-button>
</body>

The issue seems to be that if a script element with content (either inline or via a src attribute) occurs after the custom element import, it causes the custom element's initialization method to run too early (at the point in the doc where the script element is encountered).

jason0x43 avatar Dec 15 '17 15:12 jason0x43

Is this still an issue @jason0x43?

agubler avatar Jul 04 '18 09:07 agubler