Common Front-End Animation and Interaction Patterns
Practical patterns for image lazy loading, event debouncing and throttling, and delayed hover interactions.
Lazy-loading images
Many sites load images only as the user scrolls down. This behavior is commonly implemented with jQuery’s lazyLoad or scrollLoading plugin. Images outside the browser’s viewport are not loaded until the user scrolls to their position. On long pages containing many images, lazy loading improves initial page speed. It also avoids a burst of HTTP requests that may cause individual images to fail and display an ugly “X”.
How it works
<img src="placeholder.gif" data-original="real.jpg">Sites with lazy loading usually display a default placeholder, as Youku and Bilibili do. This prevents the page structure from jumping, or broken-image icons appearing briefly, when the user scrolls quickly. In the example above, the real source URL is stored in the custom data-original attribute.
The implementation calculates the rectangle of the browser viewport—its offsets from the top and left—and the rectangle occupied by each image. If the rectangles intersect, it copies data-original into src, causing the real image to load. Consult the relevant plugin source for the finer details.
// Return whether two rectangles intersect.function intens(rec1, rec2){ var lc1, lc2, tc1, tc2, w1, h1; lc1 = rec1.left + rec1.width / 2; lc2 = rec2.left + rec2.width / 2; tc1 = rec1.top + rec1.height / 2 ; tc2 = rec2.top + rec2.height / 2 ; w1 = (rec1.width + rec2.width) / 2 ; h1 = (rec1.height + rec2.height) / 2; return Math.abs(lc1 - lc2) < w1 && Math.abs(tc1 - tc2) < h1 ;}Preventing rapid repeated events
Here, “trigger” effectively means execution. The main concept is function throttling.
Front-end requirements often limit an event to one execution within a short period. Examples include the Ajax request behind a form submission and carousel navigation. Many carousels cannot animate as quickly as you can click, so their event logic must handle rapid repeated input.
function delay_exec(fn, wait) { if (_timer['id']) { window.clearTimeout(_timer['id']); delete _timer['id']; }
return _timer['id'] = window.setTimeout(function () { fn(); delete _timer['id']; }, wait);}
var _timer = {};$("#myid").bind("click", function(){ delay_exec(function(){}, 300);})This version handles only the final click. Each new click clears and recreates the timeout, continually postponing execution until clicking stops.
Another approach handles only the first click: no matter how often the user clicks during the specified interval, the function runs once. A plugin named throttle is designed for this. Its source is short and worth reading.
Showing information on hover
On Weibo and forums, hovering over a name may show a profile card, while moving across it quickly shows nothing. A commonly used jQuery plugin for this behavior is hoverIntent. More on that later.