Prevent image loading with MutationObserver

Edit: this is not actually reliable due to the way that various browsers will try to pre-emptively fetch resources as they parse an HTML document, as confirmed by Jake Archibald of the Chrome dev team.

It turns out that if you place a MutationObserver in the <head> (or presumably even in the <body> before any <img> elements), and have it start observing right away it will be able to remove the src before the browser downloads the image, thus allowing for lazy loading and other optimizations.

I put this in <head> and normal <img> tags in <body>. - No image requests visible in Firefox dev tools - Safari shows requests but 0 bytes transferred - Chrome seems to get 4 kb over the wire before calling it quits

Code language: JavaScript

const observer = new MutationObserver(mutations => {
  mutations.forEach(mutation => {
    Array.from(mutation.addedNodes)
      .filter(node => node.tagName === 'IMG')
      .forEach(img => {
        img.dataset.src = img.src;
        img.src = '';
      });
  });
});
 
observer.observe(document.documentElement, {
  childList: true,
  subtree: true
});