- Small: about 1 kb minified.
- Fast: it executes in less than 5ms even on mobile devices. (Initial cost, not per event cost.)
How it is delivered:
- Because of its size, we recommend delivering Qwikloader in an inlined
<script>tag. This way, the browser does not have to pay the cost of creating another connection to the server.
- Register global browser events.
- If an event occurs, search the DOM for the corresponding event attribute pointing to the QRL that should be lazy-loaded.
- Lazy-load the event handler and execute it.
How does it work
Below you can find simple HTML with Qwikloader and a button with associated behavior.
<html> <body q:base="/build/"> <button on:click="./myHandler.js#clickHandler">push me</button> <script> /* Qwikloader */ </script> </body> </html>
- The browser downloads the HTML and executes the inlined Qwikloader script. The Qwikloader sets up global listeners for all browser events.
- The user clicks on the
<button>. The browser generates a
clickevent that bubbles up the DOM until the Qwikloader's global listener intercepts it.
- The Qwikloader retraces the event path and searches for
on:clickattribute on the elements.
- The Qwikloader uses the
q:baseattributes along with the
document.baseURIto build a full URL for fetching the lazy-loaded handler. Assuming the original page was served up from
http://localhost/the fetch URL becomes
- Qwikloader retrieves the
clickHandlersymbol, exported from
http://localhost/build/myHandler.jsand invokes it.
Events and the Qwikloader
The registration of the listener creates two problems in the context of SSR/SSG that Qwik needs to solve. (For context, remember that Qwik is resumable, that is, it can continue executing the application from where the server paused without being forced to download and execute code eagerly.)
- listener location: Qwik needs to know where the events are in the HTML which came from the SSR/SSG.
- listener code: Qwik needs to know what code should run if the event is triggered.
Without the above information, Qwik would be forced to download the component template and execute it so that the listener location and closure can be recovered. This process is known as hydration, and Qwik explicitly tries to avoid hydration.
Qwik serializes the event listeners into the DOM in the form of QRLs. For example:
<div> <button on:click="./chunk-a.js#Counter_button_onClick">0</button> </div>
The critical thing to notice is that Qwik generated an
on:click attribute, containing the value
./chunk-a.js#Counter_button_onClick. In the above example the
on:click attribute solves the listener location problem, and the attribute value solves the listener code problem. By serializing the listeners into the HTML Qwik applications do not need to perform hydration on startup.