Detecting Failed JavaScript File Imports on Webpage

I’m working on a website that uses several JavaScript files. Here’s what my script tags look like:

<script src="/assets/main.js"></script>
<script src="/assets/utils.js"></script>
<script src="/assets/animations.js"></script>
<script src="/assets/api.js"></script>
<script src="/assets/plugins.js"></script>

I’m wondering if there’s a way to check if any of these files fail to load (like if they return a 404 error). I don’t want to manually test each one. Is there a tool or method to automatically detect missing JavaScript imports? Any suggestions would be really helpful!

I’ve encountered this issue in my projects before. One effective solution is to implement a JavaScript function that checks the status of each script after the page loads. Here’s a basic implementation:

window.addEventListener(‘load’, function() {
var scripts = document.getElementsByTagName(‘script’);
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (script.src && !script.hasAttribute(‘data-loaded’)) {
console.error('Failed to load: ’ + script.src);
}
}
});

This function loops through all script tags, checking if they have a ‘src’ attribute and haven’t been marked as loaded. You’d need to add a ‘data-loaded’ attribute to each script that loads successfully using the onload event. This method provides a centralized way to detect and log any script loading failures.

hey, i’ve dealt with this before! you can use the onerror attribute on your script tags to catch loading failures. like this:

this’ll log errors in the console for any file that doesn’t load. hope this helps!

As someone who’s been in web development for a while, I’ve found that using the browser’s built-in DevTools is incredibly handy for this kind of issue. Open up the Network tab and refresh your page. It’ll show you all the resources being loaded, including your JavaScript files. Any failed loads will be highlighted in red, making it easy to spot problematic imports at a glance.

For a more programmatic approach, you could also use the window.addEventListener(‘error’) method to catch and log any script loading errors. This way, you can set up a single listener instead of adding onerror attributes to each script tag.

Remember, though, that network issues can sometimes cause false positives, so it’s always good to double-check before assuming a file is actually missing.