Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Should use intersection observer when possible #13

Closed
tjoskar opened this issue Jun 11, 2016 · 3 comments
Closed

Should use intersection observer when possible #13

tjoskar opened this issue Jun 11, 2016 · 3 comments

Comments

@tjoskar
Copy link
Owner

tjoskar commented Jun 11, 2016

Listen for scroll events are expensive. Use intersection observer instead.

https://developers.google.com/web/updates/2016/04/intersectionobserver
https://wicg.github.io/IntersectionObserver/

tjoskar pushed a commit that referenced this issue Jul 25, 2016
@tjoskar
Copy link
Owner Author

tjoskar commented Jul 25, 2016

Do something like this:

let observer;

// create a single observer for all images
function getObserver(loadImageAndSetLoadedClass, scrollTarget, offset) {
  if (observer) return observer;
  observer = new IntersectionObserver(changes => {
    changes.forEach(change => {
      loadImageAndSetLoadedClass(change.target);
      observer.unobserve(change.target);
    });
  }, {
    root: scrollTarget,
    rootMargin: offset + 'px'
  });
  return observer;
}

// For each image
getObserver(console.log.bind(console), window, 100).observe(this.elementRef);

@ghost
Copy link

ghost commented Jun 1, 2017

The problem is it's hard to debounce the scroll with the IntersectionObserver , it's not meant to be used like that. So it's more made for sentinel elements

https://developers.google.com/web/updates/2016/04/intersectionobserver

Intersect all the things!

No! Bad developer! That’s not mindful usage of your user’s CPU cycles. Let’s think about an infinite scroller as an example: In that scenario, it is definitely advisable to add sentinels to the DOM and observe (and recycle!) those.

@tjoskar
Copy link
Owner Author

tjoskar commented Jun 6, 2017

Yeah, you are right. We have to create a new IntersectionObserver for every image which will be much more expensive then the current solution (scroll).

Thanks for your feedback!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant