IntersectionObserver API, whether the listener element into the visible region

When web development, often need to know whether an element into the "viewport" (viewport), that is, the user can not see it.

Green squares on the map constantly rolling, the top will prompt its visibility.

The traditional method is to realize, after listening to scroll event, call the target element (green squares) of getBoundingClientRect () method, to get it corresponds to the coordinates of the upper left corner of the viewport, and then determine whether or not within the viewport. The disadvantage of this method is that, due to the intensive scroll event occurs, computationally expensive, likely to cause performance problems.

There is currently a new IntersectionObserver API, you can automatically whether "watch" element visible, Chrome 51+ have support. Since the visible (visible) is the nature of the target element to produce a cross-viewport area, so the API called "cross viewer."

A, API
its usage is very simple.

var io = new IntersectionObserver (callback, option);
the above code, IntersectionObserver the constructor provided by the native browser, accepts two parameters: callback callback function is the visibility of changes, option is a configuration object (the parameter is optional) .

The return value is a function configuration example of the viewer. observe the method of Example DOM node may specify which observation.

// start observation
io.observe (document.getElementById ( 'example') );

// stop watching
io.unobserve (element);

// Close viewer
io.disconnect ();
the above code, observe parameter is a DOM node object. If you want to observe a plurality of nodes, you should call this method multiple times.

io.observe (Elementa);
io.observe (elementB);
two, callback parameter
when the change in visibility of the target element, it calls the callback function of the callback observer.

callback will generally trigger twice. A target element is just entering the viewport (beginning visible), and once completely left viewport (start invisible).

IntersectionObserver new new IO = var (
entries It => {
the console.log (entries It);
}
);
the above code uses a callback function written arrow. Parameters callback function (entries It) is an array, each member is a IntersectionObserverEntry object. For example, if there are two objects to be observed while visibility changes, there will be two entries It array members.

Three, IntersectionObserverEntry objects
IntersectionObserverEntry object provides information on the target element, a total of six properties.

{
Time: 3893.92,
rootBounds: {ClientRect
bottom: 920.,
height: 1024,
left: 0,
right: 1024,
Top: 0,
width: 920.
},
boundingClientRect: ClientRect {
// ...
},
intersectionRect: {ClientRect
/ / ...
},
intersectionRatio: 0.54,
target: Element
}
meaning of each property is as follows.

time: time variation of the occurrence of visibility, a high-precision time, in milliseconds
target: the target element is observed, is a DOM node object
rootBounds: rectangular area information of the root element, the return value getBoundingClientRect () method, If there is no root element (i.e., the viewport scrolling directly to), null is returned
boundingClientRect: rectangular area of the target elements
intersectionRect: information of the target element with the viewport (or root element) of the intersection region
intersectionRatio: the target element is visible scale , i.e. intersectionRect boundingClientRect proportion of 1 is completely visible, invisible or less completely 0

The figure, boxes represent the gray level of the viewport, the target element is dark red areas represent four observed. Their respective intersectionRatio figures have been noted.

I wrote a Demo, demo IntersectionObserverEntry object. Note that this can only be run in Demo Chrome 51+.

Four examples: lazy loading (lazy load)
Sometimes, we want some static resources (such as images), only the user scroll down until you load them into the viewport, so you can save bandwidth and improve page performance. This is called "lazy loading."

With IntersectionObserver API, it is very easy to achieve.

function query(selector) {
return Array.from(document.querySelectorAll(selector));
}

var observer = new IntersectionObserver(
function(changes) {
changes.forEach(function(change) {
var container = change.target;
var content = container.querySelector('template').content;
container.appendChild(content);
observer.unobserve(container);
});
}
);

Query ( 'the lazy-loaded.') forEach (function (Item) {.
observer.observe (Item);
});
the code above, only when the target area is visible, only the template content into the DOM true, causing static resource loading.

Five examples: infinite scroll
infinite scroll (infinite scroll) implementation is simple.

intersectionObserver new new IntersectionObserver = var (
function (entries It) {
// if not visible, returns
IF (entries It [0] .intersectionRatio <= 0) return;
LoadItems (10);
the console.log ( 'Loaded new new items');
} );

// start observing
intersectionObserver.observe (
document.querySelector () 'scrollerFooter.'
);
Infinite scroll, it is best to have a footer bar (also called sentinels) at the bottom of the page. Once footer bar is visible, it means that the user reaches the bottom of the page, which loads a new entry on the front end of the page bar. The advantage of this is that, do not need to call again observe () method, you can keep the existing IntersectionObserver use.

Six, Option objects
second parameter IntersectionObserver constructor is a configuration object. It can set the following properties.

6.1 threshold attribute
threshold property determines when to trigger the callback function. It is an array, each member is a threshold value of [0], i.e., the cross ratio (intersectionRatio) to trigger a callback function reaches zero.

IntersectionObserver new new (
entries It => {/ * ... * /},
{
threshold: [0, 0.25, 0.5, 0.75,. 1]
}
);
the user can customize the array. For example, [0, 0.25, 0.5, 0.75, 1] when it represents a target element 0%, 25%, 50%, 75%, 100% visible triggers callback function.

6.2 root properties, rootMargin attribute
a lot of the time, will not only target elements with window scroll, the scroll will be inside the container (such as rolling in the iframe window). Rolling the container will affect the visibility of the target element, see at the beginning of this article goes schematic.

IntersectionObserver API supports the rolling container. root node attribute specifies the container where the target elements (i.e., the root element). Note that the container element must be an ancestor node of the target element.

var opts = {
root: document.querySelector('.container'),
rootMargin: "500px 0px"
};

Observer new new IntersectionObserver = var (
the callback,
the opts
);
the above code, the root attribute, and attribute except rootMargin. Margin which defines the root element, to expand or contract the size of the rectangle rootBounds, and therefore the size intersectionRect intersection region. It is defined using the CSS method, such 10px 20px 30px 40px, a value representing four directions of top, right, bottom and left.

After this set, whether it is a window scrolling or rolling the container, as long as the target element is visible changes, it will trigger the viewer.

Seven, pay attention to point
IntersectionObserver API is asynchronous, not with the goal of rolling elements synchronized trigger.

Specification states that to achieve IntersectionObserver should adopt requestIdleCallback (), that is, only the thread idle down, will perform the viewer. This means that the priority of this observation is very low, only to perform other tasks completed in the browser with the idle will be performed.

Guess you like

Origin www.cnblogs.com/guojbing/p/11773277.html