3/11/2019 - 5:22 PM

Create DOM IMG

Note that old versions of IE don't create a proper image with document.createElement(), and old versions of KHTML don't create a proper DOM Node with new Image(), so if you want to be fully backwards compatible use something like below.

Also be slightly wary of document.body.appendChild if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild).

To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page

as the body's first child and put any tracking/preload images you don't want to be visible in there.

// IEWIN boolean previously sniffed through eg. conditional comments

function img_create(src, alt, title) {
    var img = IEWIN ? new Image() : document.createElement('img');
    img.src = src;
    if ( alt != null ) img.alt = alt;
    if ( title != null ) img.title = title;
    return img;