Lazy loading in fetch

Here are some text examples related to data fetching and lazy loading:

Fetching data from an API:

fetch('https://api.example.com/data') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error('Error fetching data:', error); });


Lazy Loading in React using React.lazy():

const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); }


Lazy Loading on Scroll (Infinite Scrolling):

window.addEventListener('scroll', () => { if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 500) { fetchMoreData(); // Fetch more data when the user scrolls near the bottom } }); function fetchMoreData() { fetch('https://api.example.com/moreData') .then(response => response.json()) .then(data => { console.log(data); }); }


Using Intersection Observer API for Lazy Loading:

const observer = new IntersectionObserver((entries) => { entries.forEach(entry => { if (entry.isIntersecting) { loadData(); // Load data when the element becomes visible } }); }); observer.observe(document.querySelector('#lazy-load-element')); function loadData() { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)); }


These examples demonstrate different ways to handle data fetching and lazy loading in JavaScript. Let me know if you need further explanations!

Comments

Popular posts from this blog

Cholesterol finishes

Narcotics

Economic paradoxes