How to wait for page to load in JavaScript?

Learn how to effectively manage page load times in JavaScript to ensure smooth data extraction processes. This guide provides essential techniques for handling dynamic content and synchronization challenges in web environments.

Best practices

  • Use the `DOMContentLoaded` event to run JavaScript as soon as the HTML document has been fully loaded, without waiting for stylesheets, images, and subframes to finish loading.

  • Employ the `window.onload` event to execute JavaScript code only after the entire page (including all dependent resources such as images and stylesheets) is fully loaded.

  • Incorporate jQuery's `$(document).ready()` method for a simple and cross-browser compatible way to ensure all DOM elements are fully accessible before running script, provided jQuery is included in your project.

  • Regularly check `document.readyState` within a function and use `setTimeout` for periodic checks until the state indicates that the document is fully loaded, which is useful for dynamic content.

// Method 1: Using DOMContentLoaded event
document.addEventListener('DOMContentLoaded', function() {
console.log('Page fully loaded');
});

// Method 2: Using window load event
window.onload = function() {
console.log('All resources finished loading');
};

// Method 3: Using jQuery (if included in your project)
$(document).ready(function() {
console.log('Page ready with jQuery');
});

// Method 4: Checking document.readyState
function checkReadyState() {
if (document.readyState === 'complete') {
console.log('Page loaded via readyState');
} else {
setTimeout(checkReadyState, 100); // Check every 100ms
}
}
checkReadyState();

Common issues

  • Ensure your JavaScript code accounts for different loading states by using `document.readyState` and setting up a recursive check with `setTimeout` to handle dynamically loaded content.

  • Optimize page load handling by debouncing or throttling your load event functions, especially when dealing with heavy scripts or multiple API calls to prevent performance issues.

  • For modern web applications, consider using the `Promise` or `async/await` syntax with `fetch` API calls within your load event handlers to manage asynchronous operations more effectively.

  • Avoid using jQuery's `$(document).ready()` if you are working on performance-critical applications, as native JavaScript methods like `DOMContentLoaded` are generally faster and do not require an additional library.

// Inorrect: Using only DOMContentLoaded for apps that load resources after DOM is ready
document.addEventListener('DOMContentLoaded', function() {
console.log('May not be fully ready');
});

// Correct: Using document.readyState to ensure everything is loaded
function checkReadyState() {
if (document.readyState === 'complete') {
console.log('Fully loaded');
} else {
setTimeout(checkReadyState, 100);
}
}
checkReadyState();

// Inorrect: Multiple event listeners without throttling
window.addEventListener('load', heavyFunction);
window.addEventListener('load', anotherHeavyFunction);

// Correct: Throttle event calls to avoid performance issues
let isExecuted = false;
window.onload = function() {
if (!isExecuted) {
heavyFunction();
anotherHeavyFunction();
isExecuted = true;
}
};

// Inorrect: Using older callback pattern with load events
window.onload = function() {
fetch('https://api.example.com/data').then(function(response) {
response.json().then(function(data) {
console.log(data);
});
});
};

// Correct: Using async/await for better readability and error handling
window.onload = async function() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Failed to load data:', error);
}
};

// Inorrect: Using jQuery's $(document).ready() in a performance-critical section
$(document).ready(function() {
console.log('jQuery ready');
});

// Correct: Using native JavaScript DOMContentLoaded for better performance
document.addEventListener('DOMContentLoaded', function() {
console.log('Native JS ready');
});

Try Oyxlabs' Proxies & Scraper API

Residential Proxies

Self-Service

Human-like scraping without IP blocking

From

8

Datacenter Proxies

Self-Service

Fast and reliable proxies for cost-efficient scraping

From

1.2

Web scraper API

Self-Service

Public data delivery from a majority of websites

From

49

Useful resources

Get the latest news from data gathering world

I'm interested