Home >Web Front-end >JS Tutorial >Can JavaScript Ping a Server Without Using External Libraries?
Can Javascript Ping a Server?
When creating web applications, it becomes necessary to determine the availability of external servers. While server-side scripts can easily perform this task using commands like "ping", Javascript's capabilities in this area have been limited.
However, an ingenious method has emerged utilizing the native Image object. By loading an image from the target server, Javascript can exploit the built-in mechanisms for fetching resources to determine server availability.
Implementation
The following code snippet illustrates the main function for executing the ping:
function Pinger_ping(ip, callback) { if(!this.inUse) { this.inUse = true; this.callback = callback this.ip = ip; var _that = this; this.img = new Image(); this.img.onload = function() {_that.good();}; this.img.onerror = function() {_that.good();}; this.start = new Date().getTime(); this.img.src = "http://" + ip; this.timer = setTimeout(function() { _that.bad();}, 1500); } }
The function creates an image object and sets listeners for the "onload" and "onerror" events. The image is then loaded from the target server, and a timeout is set to handle the case where the server does not respond. Based on the result, the "good()" or "bad()" methods are called to indicate server availability.
Benefits
This technique offers several advantages:
Updates
The solution presented may experience compatibility issues with newer browsers. For the latest updates and alternative solutions, refer to the included GitHub repository:
[https://github.com/jdfreder/pingjs](https://github.com/jdfreder/pingjs)
The above is the detailed content of Can JavaScript Ping a Server Without Using External Libraries?. For more information, please follow other related articles on the PHP Chinese website!