hyperHTML seemingly fails to call (attach?) onload events

150 views Asked by At

I'm attempting to dynamically conditionally load additional JavaScript while using hyperHTML. I've narrowed the failure to the onload event.

Here's an attempt at a minimal, complete, and verifiable example:

class ScriptLoader extends hyperHTML.Component {
  onload(event) {
    notie.alert({ text: "notie loaded" });
  }
  render() {
    return this.html`
      <script
        src=https://unpkg.com/notie
        type=text/javascript
        async=false
        onload=${this}
      />
    `;
  }
}

hyperHTML.bind(document.body)`
  <h2>onload test (notie)</h2>
  ${new ScriptLoader}
`;
<script src="https://unpkg.com/[email protected]/min.js"></script>

As you can see notie.alert is never called, even though the script is inserted correctly.

This some process works correctly using vanilla JS with addEventListener('load', and appendChild(.

1

There are 1 answers

1
Andrea Giammarchi On BEST ANSWER

Update this was an issue with Firefox and Web (Safari) considering death nodes scripts injected via innerHTML, even if through a template and after imported.

That means the issue was not with the onload per-se, rather the fact no network request was ever triggered so that onload would never happen indeed.

As you can verify now in the Code Pen eaxmple, which uses your exact same snippet I rewrite in part to make SO happy about me linking Code Pen, both Firefox and Safari, as well as Chrome and Edge should work just fine.

hyperHTML.bind(document.body)`
  <h2>onload test (notie)</h2>
  ${new ScriptLoader}
`;

I am keeping part of the old edit just to make you, or any other reader, aware of a little caveat that JSX affectionate might overuse.


There is one thing you should be careful with: hyperHTML does not parse HTML and <script/> is not valid HTML.

You are risking to find nodes where you shouldn't if you don't close non-void tags regularly, and this is beyond hyperHTML capabilities, unfortunately how HTML works in general.

<p/><b>unexpected</b>

I understand for this demo case you had to do that or the parse would complain with a closing script in the page but remember, you can always do this instead, when necessary:

`<script><\x2fscript>`