mirror of
https://github.com/umami-software/umami.git
synced 2026-02-08 14:47:14 +01:00
Check visibility performance optimization.
This commit is contained in:
parent
418793feaf
commit
cb7f267212
7 changed files with 172 additions and 67 deletions
34
components/CheckVisible.js
Normal file
34
components/CheckVisible.js
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import React, { useState, useRef, useEffect } from 'react';
|
||||
|
||||
function isInViewport(node) {
|
||||
return (
|
||||
window.pageYOffset < node.offsetTop + node.clientHeight ||
|
||||
window.pageXOffset < node.offsetLeft + node.clientWidth
|
||||
);
|
||||
}
|
||||
|
||||
export default function CheckVisible({ children }) {
|
||||
const [visible, setVisible] = useState(false);
|
||||
const ref = useRef();
|
||||
|
||||
useEffect(() => {
|
||||
const checkPosition = () => {
|
||||
if (ref.current) {
|
||||
const state = isInViewport(ref.current);
|
||||
if (state !== visible) {
|
||||
setVisible(state);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
checkPosition();
|
||||
|
||||
window.addEventListener('scroll', checkPosition);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('scroll', checkPosition);
|
||||
};
|
||||
}, [visible]);
|
||||
|
||||
return <div ref={ref}>{typeof children === 'function' ? children(visible) : children}</div>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue