I was driven to madness by the sheer power of these three lines of JavaScript code

let image = new Image();

image.onerror = function () { 
    if (! image) return;
    image = undefined;
    alert("123.456.789.012 is ONLINE"); 
}

image.onload = image.onerror;

image.src = "http://123.456.789.012/123.jpg";

setTimeout(function () { 
    if (! image) return;
    image = undefined;
    alert("123.456.789.012 is OFFLINE"); }, 5000); 
}

[1] 123.456.789.012 is a host, it could be online or offline. This script is designed to determine its status.

[2] The file named "123.jpg" does not exist in the system.

[3] I am struggling with understanding these three lines of code:

if (! img) return;
img = undefined;
alert("123.456.789.012 is ONLINE"); or alert("123.456.789.012 is OFFLINE");

Could someone clarify the purpose of these lines?

Answer №1

Let's break this down step by step

if (! img) return;

If there is no image, we exit the function.

img = null

We reset the img variable to null.

alert("xxx.xxx.xxx.xxx is UP");

A pop-up message with the text "xxx.xxx.xxx.xxx is UP" will be displayed.

This method of checking for the existence of an image may seem unusual. Another way to achieve the same result is:

var newImg = new Image()
newImg.addEventListener('load', function(){alert('xxx.xxx.xxx.xxx is UP')})
newImg.addEventListener('error', function(){alert('xxx.xxx.xxx.xxx is DOWN')})
newImg.src="http://xxx.xxx.xxx.xxx/123.jpg";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Updating CSS stylesheets dynamically when onchange event occurs

I am currently able to dynamically change style rules using JS, but I feel that this is limiting. I would prefer to be able to swap entire CSS stylesheet files easily. Do you have any suggestions on how to accomplish this? Here is my code: <label>T ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

What is the best way to add external javascript files to bookmarklets?

I have been developing a CDN for a collection of scripts that I created for my job. Previously, I had to distribute these scripts individually and each user would have to download and install them on their own computer. Now, I am transitioning them to an A ...

Page freezing due to JQuery scroll event

I successfully implemented a trigger that checks if an element is within the visible viewport and added it to the scroll event. While this works smoothly on some pages, I noticed that on larger pages it causes the page to freeze. In Firefox, I experienced ...

Getting it Right: Harnessing Computed Properties in VueJS

How can I organize my data effectively when dealing with computed properties that have different values? computed: { totalCoin() { const state = this.$store.state.ApiState.totalCoin let val if (state === 0) { val = 0 } else if (stat ...

How can I retrieve the Azure subscription IDs of the currently logged in user using @azure/msal-angular?

I successfully authenticated a user using @azure/msal-angular and received the id_Token, access_Token and tenant Id. Now I am looking to retrieve the logged in user's azure subscriptions. Is there a way to achieve this through msal or are there any Ja ...

Custom JavaScript clock designed for the Lockscreen of jailbroken iPhones

I am struggling with getting my JavaScript code to display the time correctly on my HTML Lockscreen. After looking at a few examples, I noticed that others are using document.getElementById() instead of document.write() and pushing it to a div. I attempt ...

Limit the text within a div to just two lines

I am facing an issue with the text size displayed in the image attached. Initially, the text is not styled with CSS. https://i.sstatic.net/00BmI.png To meet a requirement limiting the text to two lines only, I have implemented the following CSS code: { ...

javascript assign array to object key

Looking at this basic array: const arr = [ { "id": 2, "color": "red" }, { "id": 1, "color": "blue" }, { "id": 2, "color": "yellow" ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

Halt the execution of a function upon clicking a div element

I'm currently working on a function that needs to be stopped when a div with the class "ego" is clicked. This function toggles the visibility of the header based on the scroll position and should only run by default. Below is the code snippet: $("#e ...

I need to figure out how to nest a div inside of a ul-li-a and ensure that the text inside the

In my search button, I have a cached list of options. When I select one, it should trigger the menu and choose the correct option. However, I am having trouble comparing the innerText of a div with the selected option from the search area. Both a and div e ...

Locating numerous occurrences of a specific string within an array and rearranging them

I am facing an issue with organizing data stored in the 'names' variable within the code snippet. The task at hand involves converting a string into an array, rearranging the elements within the array to ensure the text is in the correct order. W ...

Step-by-step Guide on Utilizing Bootstrap Table

Currently, I am in the process of fetching data from an API and displaying it in a tabular format using JavaScript. While I have successfully retrieved the data, I'm facing an issue with applying Bootstrap styling to the table headers. async functi ...

The state in useState is failing to update correctly following selections made within the dropdown menus

I am currently facing an issue with my dropdown disabling function, which is not enabling the dropdown properly. I suspect that this is due to asynchronous problems stemming from the use of useState. const [homeSelect, setHomeSelect] = useState('Home& ...

The process of generating vue-cli-plugin-prerender-spa encountered an issue where the error was not found within the

I have successfully integrated this plugin into my laravel-vue application and configured it within the laravel mix's webpack.mix.js file. After running it via npm (using watch, dev, and prod modes), I encountered no errors. However, upon inspecting ...

Having difficulty uploading an image to Facebook through the graph API

I have a requirement to upload a photo to Facebook using the Javascript SDK, but I am experiencing some difficulties: Firstly, FB.login(function (response) { if (response.authResponse) { va ...

Is it just me or does my node server come preconfigured with CORS enabled? What am I overlooking here?

I have a simple node and express server set up here. Surprisingly, even without any middleware, I am able to successfully log the response from an axios request made to google.com. Doesn't this usually trigger a cors error, requiring some form of midd ...

Storing data in a JavaScript object without updating it in the Firebase database

There exists a node called reader rankings with a total of 14 ranks. When attempting to calculate points using static code, the process functions smoothly. Below is a snippet of the code: rank_r = getReaderRank(parseFloat(oldPointsOfReder)); userDataRe ...