search ]

How to Add Infinite Scroll to WordPress with JavaScript

Infinite scroll is a popular feature in modern web design, allowing content to load dynamically as users scroll down the page. This can enhance user engagement and reduce load times by only loading content when needed.

In this tutorial, I will show you how to implement infinite scroll in WordPress using JavaScript and AJAX without relying on a plugin.

Just saying that there’s also a post about adding AJAX Load More Button.

Why Use Infinite Scroll?

Infinite scroll can improve user experience by removing the need for pagination. It’s especially useful for blogs or content-heavy websites where users can browse more content without clicking through pages.

Step 1: Modify Your WordPress Query

Before we can implement infinite scroll, we need to adjust the WordPress query to enable AJAX loading of more posts. Open your theme’s functions.php file and add the following code:

function my_infinite_scroll_query() {
    $args = array(
        'post_type' => 'post', // Post type to query
        'posts_per_page' => 6, // Number of posts to show per "page"
        'paged' => isset($_POST['page']) ? intval($_POST['page']) : 1,
    );

    $query = new WP_Query($args);

    if ($query->have_posts()) :
        while ($query->have_posts()) : $query->the_post();
            get_template_part('template-parts/content', get_post_format()); // Adjust based on your theme structure
        endwhile;
    endif;

    wp_reset_postdata(); // Reset post data after custom query
    die();
}
add_action('wp_ajax_my_infinite_scroll', 'my_infinite_scroll_query');
add_action('wp_ajax_nopriv_my_infinite_scroll', 'my_infinite_scroll_query');

This function creates a custom query to retrieve posts from the database. We also add two actions to handle AJAX requests for both logged-in and non-logged-in users.

Step 2: Enqueue the JavaScript

Next, we need to enqueue our JavaScript file in the theme. Open your theme’s functions.php file again and add this code:

function enqueue_infinite_scroll_js() {
    wp_enqueue_script(
        'infinite-scroll',
        get_template_directory_uri() . '/js/infinite-scroll.js',
        array('jquery'),
        null,
        true
    );

    wp_localize_script('infinite-scroll', 'infinite_scroll_params', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'current_page' => get_query_var('paged') ? get_query_var('paged') : 1,
        'max_page' => $GLOBALS['wp_query']->max_num_pages,
    ));
}
add_action('wp_enqueue_scripts', 'enqueue_infinite_scroll_js');

This function enqueues the JavaScript file we will create next and passes WordPress-related parameters like the AJAX URL and the current page number to the script.

Step 3: Create the JavaScript File

Now, create a new file named infinite-scroll.js inside your theme’s js folder and add the following JavaScript code:

jQuery(function($) {
    var canLoadMore = true;
    var currentPage = infinite_scroll_params.current_page;
    var maxPage = infinite_scroll_params.max_page;

    $(window).scroll(function() {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 300 && canLoadMore && currentPage < maxPage) {
            canLoadMore = false;
            currentPage++;
            $.ajax({
                url: infinite_scroll_params.ajax_url,
                type: 'POST',
                data: {
                    action: 'my_infinite_scroll',
                    page: currentPage
                },
                success: function(response) {
                    if (response) {
                        $('.post-list').append(response); // Adjust based on your theme's structure
                        canLoadMore = true;
                    }
                },
                error: function() {
                    console.log('Failed to load more posts.');
                }
            });
        }
    });
});

This script listens for the window’s scroll event and triggers an AJAX request when the user is near the bottom of the page. It increments the page number with each request and appends the new posts to the existing post list.

Step 4: Adjust the HTML Structure

To ensure that the AJAX response is correctly inserted into the page, you’ll need to wrap your post list in a container with a class, such as post-list. This class is referenced in the JavaScript to append the new content:

<?php
echo '<div class="post-list">';
?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
        <?php get_template_part('template-parts/content', get_post_format()); ?>
    <?php endwhile; endif; ?>
<?php
echo '</div>';
?>

Ensure the class post-list matches the one in the JavaScript so that the newly loaded posts are added to this container.

Browser Compatibility and Performance Optimization

While most modern browsers will support this JavaScript-based infinite scroll, it’s always a good idea to test it across various browsers and devices.

If you’re noticing performance issues with the scroll event firing too frequently, you can optimize the performance by using window.requestAnimationFrame() to throttle the scroll event. Here’s a quick example:

var ticking = false;

$(window).on('scroll', function() {
    if (!ticking) {
        window.requestAnimationFrame(function() {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 300 && canLoadMore && currentPage < maxPage) {
                // AJAX load more logic here
            }
            ticking = false;
        });
        ticking = true;
    }
});

This ensures that the scroll event does not fire too frequently, improving overall performance.

Adding a Fallback for Pagination

It’s a good idea to include a fallback to traditional pagination in case users have JavaScript disabled. You can do this by adding basic pagination at the bottom of your posts list, which will only appear if the infinite scroll fails or JavaScript is not enabled.

if (function_exists('the_posts_pagination')) {
    the_posts_pagination();
}

This ensures that users without JavaScript can still navigate through your content using traditional pagination links.

SEO Considerations for Infinite Scroll

While infinite scroll can improve user experience, it can pose challenges for SEO, as search engine crawlers may not be able to load the dynamically generated content. To help ensure that search engines can still crawl your content efficiently, here are a few tips:

  • Make sure your content is fully accessible via traditional pagination as a fallback.
  • Use structured data (such as Schema.org markup) to help search engines understand the content on each page.
  • Consider using the rel="next" and rel="prev" attributes on paginated links to indicate the sequence of your content.

Handling Edge Cases and Errors

It’s important to handle situations where there are no more posts to load or when an AJAX request fails. You can modify the JavaScript to check if there are more posts and display a message or a loading spinner to the user.

if (!response || currentPage >= maxPage) {
    canLoadMore = false;
    $('.load-more-message').text('No more posts to load.');
} else {
    $('.post-list').append(response);
    canLoadMore = true;
}

In the HTML, you can add a simple message container that informs users when all posts are loaded:

<div class="load-more-message"></div>

Conclusion: Why Infinite Scroll Can Benefit Your WordPress Site

Implementing infinite scroll on your WordPress site can greatly enhance user engagement, especially on content-heavy websites where users tend to browse through multiple posts.

This method offers a smooth, uninterrupted browsing experience without page reloads, improving both user experience and potentially increasing time spent on your site. Just ensure you account for SEO and accessibility to make it as efficient and inclusive as possible.

Roee Yossef
Roee Yossef

I develop pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!