Detecting and terminating slow third-party javascript requests

We use the number of tracked pixels on our website to collect statistics about our visitors. However, often some of the third-party javascript that we embed in the code is waiting for a response from their server. Often their server does not respond properly, and therefore it causes error messages, as well as problems with the timely display of HTML elements of the website, which causes huge performance problems.

Is there any way to detect when third-party javascript will not return within the desired time so that we can somehow end the call to our server and move on to the next line of code? Please note that using jQuery.delay () is not really a solution to this problem.

Handling error messages returned from their servers, we can use Try and Catch (error), but I do not know how we can force javascript to be terminated on an external server.

+4
source share
1 answer

Instead, you can load scripts using the cache:

var scriptTag = document.createElement("script"); scriptTag.type = "text/cache"; scriptTag.src = "http://thirdparty.com/foo.js"; scriptTag.onreadystatechange = scriptTag.onload = function() { if (scriptTag.readyState == "loaded" || scriptTag.readyState == "complete") { // it done loading } } 

This will cause scripts to load in the background, like an image; you can call them directly if they load. The caveat is that if you have multiple timeouts, it can consume all available outgoing connections. If you serialize third-party Javascripts only then they should make the most of one connection.

This is the method used by head.js. You can probably just use head.js, but you can add extra logic for what to do with timeouts, etc.

+2
source

Source: https://habr.com/ru/post/1380478/


All Articles