Beware of empty src (updated)

We were recently optimizing some server requests and noticed an oddity in our logs. It seemed that for every page load the index (/) of the site was mysteriously loaded as well.

The site seems to work normally but the mysterious load was wasting resources. After much greping and searching one of our talented developers tracked it down to an empty src attribute on an image. We had a placeholder image added to the DOM by a jQuery script, something like this:

$('<img src="" id="preview">');

This was inserted into the Dom and later the src was updated by other script to display an appropriate image. In browsers such as Safari and Chrome, the empty src="" actually tried to load the index of the site into the image element when it was inserted into the DOM. AS a result we saw log entries like this: - - [28/Sep/2010:10:58:34 -0400] "GET / HTTP/1.1" 200 5082 ""
    "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; en-us) AppleWebKit/534.9+ (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5"

The fix was to give it a placeholder image and boom, the problem was gone. It wasn’t easy to find so I thought I’d mention it.


After a little more experimentation and discussions with another one of our talented developers, it seems the issue only occurs if you have an empty src attribute but not if you have NO attribute. So no src attribute like this:

$('<img id="preview">');

is a better solution because it doesn’t require a server request at all.

Something else to remember is that $('<img src="" id="preview">'); will still perform the extra request even if you don’t explicitly insert the jQuery it to a document. This is because jQuery does add it to a document when it builds the element internally.