十字路口旁边有一个路口_观察路口观察员

十字路口旁边有一个路口

Intersection Observers As developing for the web has matured and JavaScript engines have become faster, one area remains a significant bottleneck - rendering. It's because of this that so many of the recent development efforts have been focused around rendering, with virtual DOM being one of the more popular examples. In 随着网络开发的日趋成熟和JavaScript引擎变得越来越快,一个领域仍然是显着的瓶颈-渲染。 因此,最近的许多开发工作都集中在渲染上,其中虚拟DOM是最受欢迎的示例之一。 在
Dojo 2, being aware of these new APIs and approaches has been a priority. But working with a new API has its challenges and the Dojo 2中 ,优先考虑这些新的API和方法。 但是使用新的API会遇到挑战,并且 Intersection Observer API is no different. Intersection Observer API也不例外。

Intersection Observers have the goal of providing "a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport." This will allow sites to lazy-load images and other media, render and remove DOM on demand as we would need for a million-row grid, and provide infinite scrolling as we may see in a social network feed.

交集观察者的目标是提供“一种异步观察目标元素与祖先元素或顶级文档的视口相交的变化的方法”。 这将使站点能够延迟加载图像和其他媒体,按需渲染和删除DOM(就像我们需要一百万行网格一样),并提供无限滚动,就像我们在社交网络Feed中看到的那样。

But Intersection Observers also solve a bigger problem not immediately obvious to us as developers and outlined in the Web Incubator Community Group's Intersection Observer explanation document: displaying ads. The Interactive Advertising Bureau has a policy that ads must be 50% visible for more than a continuous second. With third-party advertising and page-impression scripts being notorious for contributing to page bloat, this API seems all the more important.

但是Intersection Observers还解决了一个更大的问题,这对我们作为开发人员来说不是立即显而易见的,并在Web孵化器社区小组的Intersection Observer解释文档中概述:显示广告。 互动广告局制定了一项政策 ,规定广告必须在50%可见度内持续超过一秒钟。 众所周知,第三方广告和页面展示脚本会导致页面膨胀,因此该API显得尤为重要。

Should we all immediately get to work integrating Intersection Observers into our projects? Unfortunately, there are a number of challenges, inconsistencies, and bugs that currently make it just out of reach and the leading polyfill implementation has a number of outstanding issues. But that does not mean the ability to use Intersection Observers is far off and we hope that by outlining the issues, creating tests, and submitting bug reports, viable use is only a few months away.

我们所有人都应该立即着手将交叉口观察员集成到我们的项目中吗? 不幸的是,目前有许多挑战,不一致和错误使它遥不可及,并且领先的polyfill实施存在许多悬而未决的问题。 但这并不意味着使用Intersection Observers的能力就遥遥无期,我们希望通过概述问题,创建测试和提交错误报告,可行的使用距离只有几个月。

这个怎么运作 ( How it Works )

How it works Intersection Observers work in two parts: an observer instance attached to either a specific node or to the overall viewport and a request to this observer to monitor specific children within its descendants. When the observer is created, it is also provided with a callback that receives one or more intersection entries.

const observer = new IntersectionObserver((entries) = > { 
    entries.forEach(entry = > console.log(entry.target, entry. intersectionRatio));
  }); 
  observer.observe(node);
  

These entries are the heart of the API. Each has information outlining the intersection change and the node whose visibility is currently changing. Three properties are at the core of these entry objects, each providing a dimension of different information:

这些条目是API的核心。 每个节点都有概述交集变化和其可见性当前正在变化的节点的信息。 这些条目对象的核心是三个属性,每个属性提供一个不同信息的维度:

  • isIntersecting indicates whether the node assigned to the target property is visible within the observer's root

    isIntersecting指示分配给target属性的节点是否在观察者的根目录中可见

  • intersectionRatio is a number between 0 and 1 indicating the ratio of the target's view within the observer's root

    intersectionRatio比率是0到1之间的数字,指示目标视图在观察者根中的比例

  • intersectionRect is an object with numbers indicating the size with width and height, and the position with top, left, bottom, and right

    intersectionRect是一个对象,其数字表示宽度和高度,尺寸表示顶部,左侧,底部和右侧

Though the API is simple, its use can be complex and unique to each use case. Several examples are provided in the Web Incubator Community Group's Intersection Observer explanation document.

尽管该API很简单,但其用法可能很复杂,并且对于每个用例都是唯一的。 Web孵化器社区组的Intersection Observer解释文档中提供了几个示例。

问题:比率为0 ( Problem: A Ratio of 0 )

One of the easiest bugs to encounter is running into an intersection ratio of 0. It is a problem because it can happen both when a node is becoming visible and when a node is no longer visible. In the example below, when scrolling through the rows, you may notice a ratio of 0 appear occasionally. If not, scroll very slowly until the next row appears.

最容易遇到的错误之一是交叉比率为0。这是一个问题,因为它可能在节点变得可见时以及节点不再可见时发生。 在下面的示例中,滚动浏览各行时,您可能会发现偶尔会出现比率0。 如果不是,请非常缓慢地滚动直到出现下一行。

演示地址

This example is reading the intersectionRatio property of the IntersectionObserverEntry passed to the callback. It seems like a logical property to use to detect an intersection - after all, wouldn't an intersection ratio of 0 mean it's not visible? But if we have code that is only executed if this ratio is non-zero, it will never be run. Furthermore, if only a single node is being observed and by skipping the intersection ratio of 0, no other events will fire, and no content updates will be performed.

本示例正在读取传递给回调的IntersectionObserverEntryintersectionRatio属性。 似乎可以用来检测相交的逻辑属性-毕竟,相交比0表示不可见吗? 但是,如果我们有仅在该比率不为零时才执行的代码,它将永远不会运行。 此外,如果仅观察到单个节点并且跳过交叉比率0,则不会触发其他事件,也不会执行任何内容更新。

The solution to this is using the isIntersecting property which is only true if this node is, or is becoming, visible. Unfortunately, if this code was being written in TypeScript, this property, at the time of this writing, did not exist in the IntersectionObserverEntry interface, so it would be easy to miss.

解决方案是使用isIntersecting属性,该属性仅在该节点可见或变为可见时才为true。 不幸的是,如果此代码是用TypeScript编写的,那么在撰写本文时,此属性在IntersectionObserverEntry接口中不存在 ,因此很容易错过。

警告:巨子 ( Caution: Giant Child )

When creating a new Intersection Observer, a number of configuration options may be passed, including a number of thresholds that allow for an intersection entry and an associated event to be fired as the percentage of its visibility changes.

创建新的“交叉口观察者”时,可能会传递许多配置选项,包括多个阈值,这些阈值允许在其可见性百分比发生变化时触发交叉口条目和关联事件。

In the W3C specification, an intersection entry is created when "intersectionRatio is greater than the last entry in observer.thresholds" where this ratio is "intersectionArea divided by targetArea." When a node is larger than the root node observing it, this ratio will steadily increase until the child node fills it, at which point the value will never reach 1 but remain the overall ratio of their two heights.

W3C规范中 ,当“ intersectionRatio大于observer.thresholds ”中的最后一个条目时,将创建一个交集条目,其中此比率为“ intersectionArea除以targetArea 。 当一个节点大于观察它的根节点时,该比率将稳定增加,直到子节点将其填满为止,此时该值永远不会达到1,而是保持其两个高度的总比率。

This can be confusing if we are expecting intersectionRatio to steadily increase between 0 and 1, which isn't a goal of the Intersection Observer API, and has no logical way of being calculated. But even if this behavior is well understood, it should be noted that events stop firing at all once that ratio no longer changes. Even though intersectionRect.top continues to change, and could be useful to our callback, the ratio itself is not changing.

如果我们期望intersectionRatio在0和1之间稳定增加,这可能会造成混淆,这不是Intersection Observer API的目标,并且没有逻辑上的计算方法。 但是,即使这种行为已被很好地理解,也应注意,一旦该比率不再改变,事件将完全停止触发。 即使intersectionRect.top继续更改,并且可能对我们的回调很有用,但是比率本身并未更改。

In this demo, console logs show intersection entries for 3 nodes - above, giant, and below - with a large number of thresholds indicating every 1% change in intersection ratio. Pay attention to when "giant" fills the parent view and stops emitting events.

此演示中 ,控制台日志显示3个节点的交集条目-上方,巨型和下方-带有大量阈值,指示交集比率每变化1%。 请注意“巨型”何时填充父视图并停止发出事件。

演示地址

警告:事件重复或丢失 ( Caution: Duplicate or Missing Events )

Duplicate Events As the specification becomes clearer and edge cases are documented, there are going to be differences between browsers and the polyfill that should be expected and managed. Reading the discussion in
this issue illustrates some of the areas in the specification that still need work, some areas where the specification was changed because of this discussion, and even explanations by browser developers as to why decisions were made the way they were.

本期中的讨论内容将说明规范中仍需要工作的某些领域,由于该讨论而更改了规范的某些领域,甚至是浏览器开发人员对为何按原样做出决策的解释。

In this example, we can open up the console to monitor the events. At the time of this writing, we could see Firefox occasionally emitting two entries as a node became visible. Although it's more of an edge-case, in the issue linked above, there are also situations where an event may not be emitted. Until these are corrected, ensure your implementation will not break, especially with duplicate events.

此示例中 ,我们可以打开控制台来监视事件。 在撰写本文时,我们可以看到Firefox在节点可见时偶尔会发出两个条目。 尽管这更像是一种极端情况,但在上面链接的问题中,也有可能没有发出事件的情况。 在更正这些错误之前,请确保您的实现不会中断,尤其是发生重复事件时。

问题:Polyfill ( Problem: Polyfill )

Polyfill At the time of this writing, the Intersection Observer polyfill incorrectly overwrites native implementations of
IntersectionObserver due to a non-global reference. Previous versions failed to apply the polyfill where the native implementation was incorrect, meaning a patched version should be used until there is a new release.

由于非全局引用 ,“交点观察器” polyfill错误地覆盖了IntersectionObserver本地实现。 以前的版本无法在本机实现不正确的地方应用polyfill,这意味着应该使用修补的版本,直到有新版本发布为止。

The polyfill currently fires only on document scroll, window resize, and DOM mutation with a throttled/debounced intersection calculation after 100ms. An issue has been opened to add animation and transition events to cover more event types. The W3C specification notes that native intersection detection "[requires] extraordinary developer effort despite their widespread use" and so it should be expected that 100% coverage is going to be difficult to achieve.

目前,polyfill仅在文档滚动,窗口调整大小和DOM突变时触发,并会在100毫秒后进行节流/去抖动交点计算。 已打开一个问题以添加动画和过渡事件以涵盖更多事件类型。 W3C规范指出,本机相交检测“尽管需要广泛使用,但仍需要开发人员付出巨大的努力”,因此,应该期望将很难实现100%的覆盖率。

Finally, there is a situation in which the polyfill will not report an intersection. Because it is entirely event-driven, calling .observe on a node already in the DOM does not calculate intersections. We have submitted an issue that recreates this situation.

最后,存在这种情况,即polyfill无法报告相交。 因为它完全是事件驱动的, .observe在DOM中已经存在的节点上调用.observe不会计算交集。 我们提交了一个问题 ,重现了这种情况。

注意:scrollTop ( Caution: scrollTop )

While this word of warning doesn't directly relate to intersection observers, it is likely to cause grief when using a scrolling inline element. Browsers have chosen different approaches to what happens when nodes are mutated within a scrolling inline element.

尽管此警告词与路口观察者没有直接关系,但使用滚动内联元素时可能会引起悲伤。 浏览器已经选择了不同的方法来处理滚动内联元素中的节点发生突变时发生的情况。

In Chrome, adding and removing nodes will automatically adjust the scroll position of the parent, through the scrollTop property. Other browsers - Safari, for example - do not perform this calculation. Because of this, you will need to work around this limitation by manually adjusting scrollTop based on size changes to nodes that appear before the first visible row.

在Chrome中,添加和删除节点将通过scrollTop属性自动调整父级的滚动位置。 其他浏览器-例如Safari-不会执行此计算。 因此,您将需要通过根据出现在第一个可见行之前的节点的大小更改来手动调整scrollTop来解决此限制。

预后:到达目的地 ( Prognosis: Getting There )

If it can be assumed that all users visiting a rich web application will be on the latest version of the leading browsers, there is enough active development and bug-squashing to assume we'll have a stable API in the near future.

如果可以假设所有访问富Web应用程序的用户都将使用最新版本的领先浏览器,则有足够的活跃开发和漏洞消除功能,可以假定我们在不久的将来将拥有稳定的API。

But because most projects cannot make this assumption, the polyfill will have to stand in when needed. While we also expect this code to improve, there are inherent limitations to what can be calculated without having access to the rendering pipeline and native event loop. Using straightforward CSS and knowing the supported events match your use case should result in usable intersection events.

但是由于大多数项目无法做出此假设,因此在需要时必须使用polyfill。 尽管我们也希望此代码能够得到改进,但是在无法访问渲染管道和本机事件循环的情况下,可计算的内容存在固有的局限性。 使用简单CSS并知道所支持的事件与您的用例匹配,将导致可用的相交事件。

了解更多 ( Learning More )

SitePen provides web application development & consulting to enterprise teams worldwide. Connect with SitePen today to expand your team's experience, expertise and ability to achieve more.

SitePen为全球企业团队提供Web应用程序开发和咨询。 立即与SitePen联系,以扩展您的团队的经验,专业知识和取得更多成就的能力。

SitePen

翻译自: https://davidwalsh.name/intersection-observers

十字路口旁边有一个路口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值