How often have you had a web site appear to load quickly, only to find that you couldn’t actually click or scroll for a while? Sometimes a site can have a fast first paint, but if the page isn’t also interactive quickly, users can quickly grow frustrated, and even leave the page.
When executing scripts on a page, one thing we want to avoid is creating unnecessary jank for the user. This particularly true when we’re doing a lower priority task that doesn’t have to be called that exact moment. In those cases, it would be helpful to be able to delay those calls until we’re sure the browser isn’t working on something more important.
Each webpage is composed of various elements. And knowing where these elements are in relation to the viewport can be extremely helpful. For instance, this knowledge allows us to lazy load images, or to load additional content at the bottom of the page (e.g. infinite scroll). This knowledge can also helpful in determining when to trigger animations, or in reporting certain analytic information (e.g. which advertisements have been viewed, or how far down the page a user travels).
Whenever you’re listening for events on the page, it’s important to make sure that the event listeners don’t get overwhelmed with processing incoming requests. Otherwise they can quickly become a bottleneck and cause an unnecessary performance hit.
Earlier this year, as I was looking through the results of a Lighthouse audit, I came across a recommendation to use passive event listeners. Since I didn’t know what this was referring to, I did a little investigation, and the following is what I discovered.