AJAX and Images

Okay so I recently figured this out, fixed it on my scripts, forgot about it, was just reminded, realized I ought to document/share. So this is getting posted here and a couple other places.

When you do a fetch() or $.get() the browser only fetches that specific page, and doesn’t bring along any external/linked files. One extra server request on the page – so far, so good, and we know to expect not to get the external javascript coming along for the ride, etc

HOWEVER.

The moment you use new DOMParser().parseFromString(data, 'text/html'); or $(data) it will pre fetch every image on that page even though you haven’t inserted any of them onto the visible page yet.

Depending on which page you’re fetching, it could only make a trivial difference, but equally it can easily result it fetching hundreds of images, even if you don’t actually want to use any of them. Worse, that’s potentially hundreds of broken images who’s requests have to time out before the next ‘on page load/document ready’ javascript will execute (which is how I realized something fishy was going on).

The solution is to make the images sourceless (so far as the browser is concerned) before parsing the html, and then restore the src value for any images you actually want shown.

$.get('/?act=Members&max_results=1000', function (data) {
    data = data.replace(/src=/g, "data-src="); /* prevent image prefetching!! */
    let doc = new DOMParser().parseFromString(data, 'text/html');

    /* your code */

    $(".thing.inserted.onto.page img[data-src]").each((i,e) => { 
         e.src = e.dataset.src; 
    });
});

(I can’t claim credit for the solution, but I’ve gone and forgotten which blog I found it on. Sorry.)