getButterfly
Resume

NAVIGATION

ATTRIBUTION

getButterfly
Dublin, Ireland

All Content Copyright ©2018
getButterfly

Image Beacons

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.

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

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

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

Thats 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 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.

Find more JavaScript tutorials, code snippets and samples here or more jQuery tutorials, code snippets and samples here.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.


My Battle Tested Recommendations

Jetpack
Dreamhost
WordPress.com
CodeCanyon
SEMrush

Disclaimer: These recommendations contain affiliate links.