Benefits of AJAX and REST API for Website Speed
1. Faster Initial Page Load
Traditional methods, such as using WP_Query
in PHP, load all content server-side before rendering the page. With AJAX and REST API, only essential page components (HTML, CSS, and JavaScript) are loaded initially. Posts or other dynamic data are fetched after the page has rendered, resulting in a faster first contentful paint (FCP).
2. Reduced Server Load
Fetching posts using the REST API reduces the strain on the server by only retrieving the necessary data. For instance, if you request six posts (per_page: 6
), the server only sends that specific data, unlike traditional methods that might load entire datasets.
3. Dynamic Data Loading
With AJAX, additional content can be loaded as needed. For example, when implementing infinite scrolling or a “Load More” button, posts are fetched dynamically, improving user engagement without refreshing the page.
4. Smaller Data Payloads
The REST API fetches only the required fields, such as title
, link
, excerpt
, and featured_image_url
. By avoiding unnecessary data, the payload size is reduced, optimizing network usage and speeding up the page.
5. Supports Lazy Loading
Lazy loading ensures that only the visible content loads first, with additional data fetched as the user scrolls. AJAX and REST API facilitate lazy loading, improving performance metrics like Largest Contentful Paint (LCP).
6. Better User Experience
A fast-loading website keeps users engaged and provides a smooth browsing experience. AJAX updates specific parts of the page without disrupting the user’s flow, reducing bounce rates and increasing session duration.
7. Improved Browser Caching
Since JavaScript and CSS files load only once and are cached in the browser, subsequent API requests are faster. This makes the website feel snappier during navigation.
8. Scalability and Reusability
The REST API is a standardized way of fetching data, making it reusable for mobile apps, SPAs (Single Page Applications), and other platforms. This allows developers to scale the application while maintaining performance.
Try with an Example.
Create JS file post-grid.js and enqueue it inside function.php file or you can use inside your plugin file.
function enqueue_post_grid_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script(
'post-grid-script',
get_template_directory_uri() . '/assets/js/post-grid.js',
array('jquery'),
null,
true
);
// Localize script to pass the REST API URL
wp_localize_script('post-grid-script', 'wp_api', array(
'root' => esc_url_raw(rest_url()),
'nonce' => wp_create_nonce('wp_rest'),
));
}
add_action('wp_enqueue_scripts', 'enqueue_post_grid_scripts');
// Register custom field for featured image
add_action('rest_api_init', function () {
register_rest_field('post', 'featured_image_url', [
'get_callback' => function ($post) {
$image_id = get_post_thumbnail_id($post['id']);
return $image_id ? wp_get_attachment_image_url($image_id, 'full') : null;
},
]);
});
The add the below code inside your post-grid.js file
jQuery(document).ready(function ($) {
const postGrid = $('#post-grid');
// Fetch posts using the REST API
$.ajax({
url: wp_api.root + 'wp/v2/posts', // REST API endpoint
method: 'GET',
data: {
per_page: 6, // Number of posts to fetch
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', wp_api.nonce); // Security nonce
},
success: function (posts) {
let output = '<div class="post-grid-container">';
posts.forEach(function (post) {
const featuredImage = post.featured_image_url || 'default-image.jpg';
output += `
<div class="post-item">
<h2><a href="${post.link}">${post.title.rendered}</a></h2>
${featuredImage ? `<img src="${featuredImage}" alt="${post.title.rendered}">` : ''}
<p>${post.excerpt.rendered}</p>
</div>`;
});
output += '</div>';
postGrid.html(output);
},
error: function (err) {
postGrid.html('<p>Failed to load posts. Please try again later.</p>');
console.error('Error fetching posts:', err);
},
});
});
And after that add the code where you want display the post.
<div id="#post-grid"></div>
Happy Coding….