JavaScript - Measure remote pages' load times

问题: I'd like to have a very simple page on my server, which uses JS to measure the time it takes to load the login web page on several remote URLs/servers. These servers are lo...

问题:

I'd like to have a very simple page on my server, which uses JS to measure the time it takes to load the login web page on several remote URLs/servers. These servers are located around the world, and I'd like to measure the times in order to choose the fastest one for my location (i.e. the code will run client-side of course, on the user's browser).

Example:

server1.example.com: 200 ms

server2.example.com: 400 ms

server3.example.com: 2 ms

There's a lot of software that does this general idea (from simple pinging to wget, etc.), but I'm looking for JS code that I can use in a simple page which will try these requests and display the times.

The basic way I tried until now (simple Ajax requests using jQuery) doesn't work because of CORS errors. Any ideas for the simplest solution would be awesome.


回答1:

You can load images without any restrictions, so take advantage of them:

function ping(url) {
	var img = new Image(),
	start = Date.now();

	img.onload = function () {
		console.log(url, 'loaded in', Date.now() - start, 'ms');
	};

	img.src = url + '?' + Math.random();
	document.body.appendChild(img);
}

ping('https://facebook.com/favicon.ico');
ping('https://www.bing.com/favicon.ico');
ping('https://youtube.com/favicon.ico');

By the way, for accurate results, make sure the images are the same size.

  • 发表于 2018-12-27 05:32
  • 阅读 ( 203 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除