0

I wonder to use pure Javascript to check if a special URL can be connected to avoid web page loading too long.

I tried Ajax, although it works, it will throw an error into the console if the origin I required has no or unmatched "Access-Control-Allow-Origin" header.

Here is my code:

window.addEventListener('load', function() {
    (async function() {
        var cx = '016855202528329427677:gpowcz722_s';
        var gcse = document.createElement('script');
        gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
        gcse.type = 'text/javascript';
        gcse.async = true;
        var s = document.getElementsByTagName('script')[0];
        var xhr = new XMLHttpRequest();
        xhr.addEventListener('load', function() {
            s.parentNode.insertBefore(gcse, s);
        });
        xhr.addEventListener('error', function() {
            console.log("A '" + gcse.src + "' CORS error may occur here. It's not a mistake but a connection check for those don't have access to Google.");
            s.parentNode.insertBefore(gcse, s);
        });
        xhr.open('HEAD', gcse.src);
        xhr.timeout = 3000;
        xhr.send();
    })();
});

So, is there any other way to use JS to check if it can be connect to a URL without any error?

Bekcpear
  • 1
  • 1
  • Found this in an old question [Answer is here](https://stackoverflow.com/questions/4282151/is-it-possible-to-ping-a-server-from-javascript) – ruggierom Apr 20 '19 at 15:16
  • @ruggierom Thank you, but the Image() constructor will also load the request URL for a long time if it can't be accessed even if I change the source URL at setTimeout() function. – Bekcpear Apr 20 '19 at 17:28

0 Answers0