Image Beacons

on in JavaScript DOM
Last modified on

Using image beacons is one of those popular techniques that you would probably know about without knowing its name.

The technique helps in cases when you are mostly interested in sending data to the server. You can receive a response through this technique, but the nature of the method makes it ideal for cases when you are more concerned about posting data back to the server (e.g. for analytics purposes, saving user state etc).

You create in your JavaScript a new Image() object and point its src property to the script on your server. The data to be posted back to the server is added as the query string in the URL for the src property.

let img = new Image();
let data = 'name="John"';

img.onload = function () {
    console.log('Data successfully sent');
}

img.src = '/path/to/your/script/' + '?' + data;

That’s it! Notice how we don’t inject the image in the DOM.

Also in the example above, we are listening for a server response in the onload handler. If we don’t want to send any data over the wire for the client to download, we can just set the appropriate response code "204 No Content". In that case, the onload event won’t be fired.

Now, a quick laydown on the advantages/disadvantages of this method:

Pros:

  1. Crossdomain
  2. Lightweight (if no data is sent by the server)
  3. No DOM manipulation

Cons:

  1. Since the data is sent as query string, you are limited by the amount of data the string can carry

If you want a confirmation of the call, you can use xHR but otherwise, this is a cheap and easy method to send data flying.

Related posts