pingjs

JavaScript ping API for use in a web browser context. Released under the BSD-3-Clause license, see LICENSE.

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/370057/610490/pingjs.js

  1. // See LICENSE for usage information
  2.  
  3. // The following lines allow the ping function to be loaded via commonjs, AMD,
  4. // and script tags, directly into window globals.
  5. // Thanks to https://github.com/umdjs/umd/blob/master/templates/returnExports.js
  6. (function (root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof module === 'object' && module.exports) { module.exports = factory(); } else { root.ping = factory(); }
  7. }(this, function () {
  8.  
  9. /**
  10. * Creates and loads an image element by url.
  11. * @param {String} url
  12. * @return {Promise} promise that resolves to an image element or
  13. * fails to an Error.
  14. */
  15. function request_image(url) {
  16. return new Promise(function(resolve, reject) {
  17. var img = new Image();
  18. img.onload = function() { resolve(img); };
  19. img.onerror = function() { reject(url); };
  20. img.src = url + '?random-no-cache=' + Math.floor((1 + Math.random()) * 0x10000).toString(16);
  21. });
  22. }
  23.  
  24. /**
  25. * Pings a url.
  26. * @param {String} url
  27. * @param {Number} multiplier - optional, factor to adjust the ping by. 0.3 works well for HTTP servers.
  28. * @return {Promise} promise that resolves to a ping (ms, float).
  29. */
  30. function ping(url, multiplier) {
  31. return new Promise(function(resolve, reject) {
  32. var start = (new Date()).getTime();
  33. var response = function() {
  34. var delta = ((new Date()).getTime() - start);
  35. delta *= (multiplier || 1);
  36. resolve(delta);
  37. };
  38. request_image(url).then(response).catch(response);
  39. // Set a timeout for max-pings, 5s.
  40. setTimeout(function() { reject(Error('Timeout')); }, 5000);
  41. });
  42. }
  43. return ping;
  44. }));

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址