JavaScript Low Resolution Image Replacer

This is a handy, yet very simple, widget I was hacking on to replace loading or low resolution images with higher resolution ones once the document has finished loading.

How do it…

The widget is built using the jQuery plugin system and here is the complete code:

(function($) {
  var isLoaded = false,
    REPLACEMENT_CLASS = "replacement-class",
    REPLACEMENT_RCLASS = "replacement-rclass",
    REPLACEMENT_URL = "replacement-img",
    TIMER = 500;

  $(window).load(function() {
    isLoaded = true;

  function replaceImages() {
    $(this).each(function(i, el) {
      var $el = $(el);
      $el.attr('src', $;

  $.fn.replaceImages = function() {
    var $items = $(this);

    if (isLoaded) {
      $.fn.replaceImages = replaceImages;
    } else {
      setTimeout(function() {
      }, TIMER);

When adding images to the page, include a low resolution image in the src and a higher resolution image in the data-replacement-src:

<img src="<pathToALowResImage>"

Once imported, the plugin adds the method replaceImages to any jQuery collection:

$('#parentId img').replaceImages();
// ...

I have also created a little code pen to help illustrate (click rerun in the bottom right):

See the Pen JwpcB by Matt Snider (@mattsnider) on CodePen.

How it works…

With this plugin developers can load their webpages with lower resolution or loading images, and replace them with more detailed ones when the browser is available. By waiting for the window.onload event, we ensure that all images, scripts, css, and other files included with the page are loaded before we attempt to replace those images with larger, higher resolution ones. And because it’s written as a plugin, it works on any jQuery element collection.

There are three data- attributes that the plugin looks for. The most important is the data-replacement-img attribute which is required and should contain the high resolution image URL used to replace the low resolution one. The data-replacement-class can be set to any classes to add to the image after replacing the URL, and data-replacement-rclass can be set to any classes to remove after replacing the URL.

There’s more…

This plugin is useful as written, but it could benefit from an analysis of bandwidth (as mentioned in the Detecting Object Mutations by Counting Properties), with tiered higher resolution images based on the download speeds.