On improving JavaScript relation with HTML

Currently we have few basic ways of running JavaScript in the context of web page:

  1. Inline JavaScript in script tag:

    <script>
      console.log("a value");
    </script>

2) Event handler:

   <button onclick="handler(event, this)">Click</button>

3) External script:

   <script src="script.js"></script>

The HTML is parsed and evaluated at the same time from top to the bottom. Event handlers are executed when event is triggered.

Preffered ways of adding JavaScript script are 1 and 3. 2 is discouraged, because event handlers are run in global context which is considered a bad engineering practice. Recommended alternatives are:

  • attaching events in JavaScript code and operating only on a subtree of document tree,
  • use of frameworks which introduce very similar, yet slightly different syntax to support events handling.

Let's simulate situation where both alternatives are not required and we can stick with point 2 as well.

Started from the bottom now we're here 1

<div bind>a value</div>