Listening on events

A key feature of any framework is making it easy to listen to user events.

Qwik can listen on a variety of events by placing an on<Eventname>$ attribute on an element that subscribes to the corresponding browser event.

Your task is to add a click event handler on the <button> element. Start by adding the onClick$ property and bind it to a function that calls alert('Hello World!').

Understanding the Runtime

So far this may look like a normal framework behavior, however Qwik does things very differently from other frameworks.

Every time you see a $ you should be thinking, "lazy-loading happens here".

As you open the browser's developer tools, notice that no JavaScript is loaded until you click the button.

If JavaScript is required to subscribe to browser events, how does Qwik achieve this interaction without loading JavaScript?

Consider the following simplified HTML of the application below.

Tip: Click on the HTML tab to see actual HTML produced by the server.

    <button on:click="chunk-abc.js#App_onClick">
      Click Me
    <script id="Qwikloader">....</script>
  1. APIs contain the $ so the Qwik optimizer can transform your code for lazy-loading.
  • The $ is a signal to the optimizer to extract the code for lazy-loading.
  • The $ is a signal to you that lazy-loading "magic" happens at this point.
  • TypeScript rules ensure you don't skip any places where the $ should appear.
  1. The optimizer looks for the $ and extracts the function wrapped by $ into a separate lazy-loadable chunk.
  2. As the server renders the page, the JSX is executed and notices that there is a click listener. The click listener is serialized into the <button> element as on:click attribute. Qwik then knows how to hook this event back up on the client.
  3. Qwikloader scripts get inlined into HTML. The Qwikloader script sets up a global listener for all events in the browser. Qwikloader is about 1kb and executes in about 1ms.
  4. When a user clicks on the button, the Qwikloader intercepts the event and looks for an element with on:click attribute.
  5. The on:click attribute contains:
    • The URL to download the associated code.
      • To avoid delays between click and execution, Qwik prefetches the code related to the given component.
    • A symbol that is exported by the downloaded chunk that contains the function needs to execute.
  6. Once the code is downloaded the function is executed.

The above behavior is what gives Qwik applications their instant-on property (resumability) without eagerly downloading and executing code and performing hydration which is expensive.

NOTE To avoid delays between user action and response, Qwik prefetches code in the background.

Edit Tutorial