Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect and log when external JavaScript or CSS resources fail to load

I have multiple <head> references to external js and css resources. Mostly, these are for things like third party analytics, etc. From time to time (anecdotally), these resources fail to load, often resulting in browser timeouts. Is it possible to detect and log on the server when external JavaScript or CSS resources fail to load?

I was considering some type of lazy loading mechanism that when, upon failure, a special URL would be called to log this failure. Any suggestions out there?

What I think happens:

  1. The user hits our page and the server side processes successfully and serves the page

  2. On the client side, the HTML header tries to connect to our 3rd party integration partners, usually by a javascript include that starts with "http://www.someothercompany.com...".

  3. The other company cannot handle our load or has shitty up-time, and so the connection fails.

  4. The user sees a generic IE Page Not Found, not one from our server.

So even though my site was up and everything else is running fine, just because this one call out to the third party servers failed, one in the HTML page header, we get a whole failure to launch.

like image 363
Mark Richman Avatar asked Apr 16 '11 01:04

Mark Richman


2 Answers

If your app/page is dependent on JS, you can load the content with JS, I know it's confusing. When loading these with JS, you can have callbacks that allow you to only have the functionality of the loaded content and not have to worry about what you didn't load.

var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'http://domain.com/somefile.js';
script.onload = CallBackForAfterFileLoaded;
document.body.appendChild(script);
function CallBackForAfterFileLoaded (e) {
//Do your magic here...
}

I usually have this be a bit more complex by having arrays of JS and files that are dependent on each other, and if they don't load then I have an error state.

I forgot to mention, obviously I am just showing how to create a JS tag, you would have to create your own method for the other types of files you want to load.

Hope maybe that helps, cheers

like image 144
joseeight Avatar answered Oct 25 '22 08:10

joseeight


You can look for the presence of an object in JavaScript, e.g. to see if jQuery is loaded or not...

if (typeof jQuery !== 'function') {
   // Was not loaded.
}

jsFiddle.

You could also check for CSS styles missing, for example, if you know a certain CSS file sets the background colour to #000.

if ($('body').css('backgroundColor') !== 'rgb(0, 0, 0)') {
   // Was not loaded.
}

jsFiddle.

When these fail, you can make an XHR to the server to log these failings.

like image 23
alex Avatar answered Oct 25 '22 09:10

alex