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?