partizan
partizan

Reputation: 469

Detecting and terminating slow third party javascript requests

We're using number of Tracking Pixels on our website to gather stats about our visitors. However, often some of those third party javascript that we embed in code are waiting on a response from their server. Often their server is not responding properly and therefore it causes an error messages as well as problems with timely rendering the website HTML elements, which causes huge performance issues.

Is there a way to detect when a third-party javascript doesn't return within desired time so we can somehow terminate the call to their server and proceed to the next line of code? Please note that using the JQuery.delay() is not really a solution to this problem.

Handling error messages returned from their servers we can use Try & Catch(error), but I don't know how we can force termination of a javascript call to external server.

Upvotes: 4

Views: 732

Answers (1)

Scott A
Scott A

Reputation: 7834

You can load the scripts using the cache instead:

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's done loading
    }
}

This will cause the scripts to load in the background like an image; you can then call them directly if they load. The caveat is that if you have several that time out it can consume all of the available outgoing connections. If you serialize the 3rd party Javascripts only then they should at most consume one connection.

This is the technique used by head.js. You can probably just use head.js, but you may want to add some extra logic for what to do with timeouts and so on.

Upvotes: 2

Related Questions