Use the Intersection Observer API for scroll animations in WordPress
The Intersection Observer API tells you when an element enters or leaves the viewport, without a scroll listener that fires dozens of times per second. Since WordPress 5.5 images and iframes get loading="lazy" natively, so today the API is most useful for scroll-triggered animations, infinite scroll, and loading heavy embeds (maps, videos, widgets) only when they are about to be seen.
Problem: Start animations and load heavy content only when the elements scroll into view, without slowing down scrolling.
Solution: Create an IntersectionObserver with a callback, call observe() for each element, and react to isIntersecting in the callback. The threshold option sets how much of the element must be visible, rootMargin lets the callback fire a bit before the element appears.
Scroll animations
The CSS: the element is hidden and shifted until it gets the visible class. Visitors who asked the system to reduce motion get no animation:
.animate-on-scroll {
opacity: 0;
transform: translateY( 30px );
transition: opacity .6s ease, transform .6s ease;
}
.animate-on-scroll.visible {
opacity: 1;
transform: none;
}
@media ( prefers-reduced-motion: reduce ) {
.animate-on-scroll {
opacity: 1;
transform: none;
transition: none;
}
}
The script, enqueued in the footer:
const animateObserver = new IntersectionObserver( ( entries, observer ) => {
entries.forEach( ( entry ) => {
if ( entry.isIntersecting ) {
entry.target.classList.add( 'visible' );
observer.unobserve( entry.target ); // animate only once
}
} );
}, { threshold: 0.15 } ); // when 15% of the element is visible
document.querySelectorAll( '.animate-on-scroll' ).forEach( ( el ) => animateObserver.observe( el ) );
Add the class animate-on-scroll to a block in the editor (Advanced → Additional CSS class) and it appears on scroll.
Load an embed when it is close
// HTML: <div class="lazy-iframe" data-src="https://www.youtube.com/embed/VIDEO_ID"></div>
const iframeObserver = new IntersectionObserver( ( entries, observer ) => {
entries.forEach( ( entry ) => {
if ( ! entry.isIntersecting ) {
return;
}
const wrapper = entry.target;
const iframe = document.createElement( 'iframe' );
iframe.src = wrapper.dataset.src;
iframe.width = '560';
iframe.height = '315';
iframe.title = 'Video';
iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
iframe.allowFullscreen = true;
observer.unobserve( wrapper );
wrapper.replaceWith( iframe );
} );
}, { rootMargin: '200px 0px' } ); // start 200px before it enters the viewport
document.querySelectorAll( '.lazy-iframe' ).forEach( ( el ) => iframeObserver.observe( el ) );
Infinite scroll with the REST API
An empty element after the list (the “sentinel”) triggers loading of the next page. The REST URL comes from PHP, so it works in a subfolder install too: wp_localize_script( 'theme-script', 'themeData', array( 'restUrl' => esc_url_raw( rest_url( 'wp/v2/posts' ) ) ) );
const sentinel = document.querySelector( '#load-more-sentinel' );
const list = document.querySelector( '#post-list' );
let page = 2;
let loading = false;
const infiniteObserver = new IntersectionObserver( async ( entries ) => {
if ( ! entries[ 0 ].isIntersecting || loading ) {
return;
}
loading = true;
const response = await fetch( `${ themeData.restUrl }?page=${ page }&per_page=5&_fields=link,title` );
const posts = response.ok ? await response.json() : [];
if ( ! posts.length ) {
infiniteObserver.disconnect(); // no more posts
return;
}
posts.forEach( ( post ) => {
const li = document.createElement( 'li' );
const a = document.createElement( 'a' );
a.href = post.link;
a.innerHTML = post.title.rendered; // WordPress returns the title already escaped
li.appendChild( a );
list.appendChild( li );
} );
page++;
loading = false;
} );
if ( sentinel && list ) {
infiniteObserver.observe( sentinel );
}
After the last page the REST API returns an error (400), so response.ok is false and the observer is disconnected.
NOTE: All current browsers support Intersection Observer. Without it (very old browsers) the elements with animate-on-scroll would stay invisible, so if that matters, check 'IntersectionObserver' in window and add the visible class to all of them at once.