I have multiple JavaScript files included on my webpage, such as:
Is there a way to determine if any of these files are missing (returning a 404 error) without manually checking each one? I'm looking for an automated solution or a web tool that can assist with this task.
To automate the process of identifying missing JavaScript files on your webpage, you can use JavaScript itself to programmatically check the HTTP status of each file. The following example demonstrates how this can be accomplished using JavaScript's XMLHttpRequest
:
function checkScripts(urls) {
urls.forEach(url => {
const xhr = new XMLHttpRequest();
xhr.open('HEAD', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status !== 200) {
console.error(`Missing file: ${url}`);
} else {
console.log(`File loaded successfully: ${url}`);
}
}
};
xhr.send();
});
}
const scriptUrls = [
'/assets/scriptA.js',
'/assets/scriptB.js',
'/assets/scriptC.js',
'/assets/scriptD.js',
'/assets/scriptE.js',
];
checkScripts(scriptUrls);
The function checkScripts
accepts an array of script URLs. It sends an HTTP HEAD request to each script URL asynchronously and logs an error to the console if the script is missing (i.e., returns a 404 error). Note that this method requires the script to be served from the same domain, due to cross-origin policy.
Additionally, for a scalable solution or for websites with many files, consider using online tools such as GTmetrix or Pingdom, which analyze and report missing resources on web pages. These tools provide detailed reports about the loading status of all resources, including JavaScript files.