0
0
Wordpressframework~8 mins

REST API with JavaScript in Wordpress - Performance & Optimization

Choose your learning style9 modes available
Performance: REST API with JavaScript
MEDIUM IMPACT
This concept affects page load speed and interaction responsiveness by how API calls are made and handled in the browser.
Fetching data from a REST API in a WordPress site using JavaScript
Wordpress
fetch('https://example.com/wp-json/wp/v2/posts')
  .then(res => res.json())
  .then(data => {
    const html = data.map(post => `<p>${post.title.rendered}</p>`).join('');
    document.body.innerHTML += html;
  });
Builds HTML string first and updates DOM once, reducing reflows and repaints.
📈 Performance GainSingle reflow and repaint regardless of number of posts
Fetching data from a REST API in a WordPress site using JavaScript
Wordpress
const response = fetch('https://example.com/wp-json/wp/v2/posts').then(res => res.json()).then(data => { for(let i=0; i<data.length; i++) { document.body.innerHTML += `<p>${data[i].title.rendered}</p>`; } });
This code updates the DOM inside a loop, causing multiple reflows and repaints, slowing rendering and interaction.
📉 Performance CostTriggers N reflows and repaints where N is number of posts
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Updating DOM inside loopMultiple insertionsN reflows for N itemsHigh paint cost[X] Bad
Batch DOM update with single insertionSingle insertion1 reflowLow paint cost[OK] Good
Rendering Pipeline
The browser fetches data asynchronously, then updates the DOM. Multiple DOM updates inside loops cause repeated Layout and Paint stages, slowing rendering.
Layout
Paint
Composite
⚠️ BottleneckLayout and Paint due to multiple DOM changes
Core Web Vital Affected
INP
This concept affects page load speed and interaction responsiveness by how API calls are made and handled in the browser.
Optimization Tips
1Always fetch REST API data asynchronously to avoid blocking the main thread.
2Batch DOM updates by building HTML strings or using DocumentFragment before inserting.
3Avoid synchronous API calls and multiple DOM manipulations inside loops.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance problem when updating the DOM inside a loop after fetching REST API data?
AIt increases network latency
BIt blocks the API response
CIt causes multiple reflows and repaints, slowing rendering
DIt reduces bundle size
DevTools: Performance
How to check: Open DevTools, go to Performance tab, record while loading the page and fetching API data, then analyze Layout and Paint events.
What to look for: Look for multiple Layout and Paint events caused by repeated DOM updates; fewer events indicate better performance.