observerOptions

root: Element | null - the element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null.

rootMargin: string - margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections.

threshold: number - a single number between 0 and 1, which indicate at what percentage of the target's visibility the observer's callback should be executed. A value of 0 means as soon as even one pixel is visible, the callback will be run. 1 means that the threshold isn't considered passed until every pixel is visible.

retry

All the properties are optional.

count: number - specifies the number of times you want to retry. Set it to 0 will disable auto-retry.

delay: number - specifies the delay between retries in seconds.

acc: string | false - specifies how the delay should be accumulated with each retry. It accepts the following values:

'*' (default) - multiply delay after each subsequent retry by the given delay value, e.g. delay: 2 means retry will run after 2 seconds, 4 seconds, 8 seconds, and so on.

'+' - increment delay after each retry by the given delay value, e.g. delay: 2 means retry will run after 2 seconds, 4 seconds, 6 seconds, and so on.

The Smart Way to Load Images

Lazy image loading via the Intersection Observer API is good. But could it be greater to download an image only when user want to see it? Or bypass lazy loading for cached images? The answer is yes and these features already be built into react-cool-img by the debounce and cache props.

By the debounce prop, an image can wait to be downloaded while it's in the viewport for a set time. In cases where you have a long list of images that the user might scroll through inadvertently. At this time loading images can cause unnecessary waste of bandwidth and processing time.

By the cache prop, images you already have cached will abort lazy loading until user visit your app next time. Lazy loading is set up for any remaining images which were not cached. This is helpful for UX, because there's not much extra work to load cached images immediately and is an easy win for making the UI looks more intuitive.

JavaScript Availability and SEO

There're two challenges when doing lazy image loading with server-side rendering. One is Javascript availability the other is SEO. Fortunately, we can use <noscript> tag to solve these problems. It will render the actual image as fallback if Javascript is disabled thus user won't see the image which be stuck with the placeholder. Moreover, the <noscript> tag ensure the image is indexed by search engine bots even if they cannot fully understand our JavaScript code. Take a look at how magic happens.