JSFiddle - React, Tailwind, and code Playground

by Kevin Kirchner

HTML

Image's current width: <span id="image_current_width"></span><br/>
Viewport Width: <span id="viewport_width"></span><br/>
Image's native width: <span id="image_actual_width"></span><br/><br/>

<img src="http://placekitten.com/400/400" width="400" height="400" data-retina-src="http://placekitten.com/800/800" alt="" style="" />

CSS

img { width: 100%; height:auto; }

JavaScript

(function($){

    // The pixel ratio for which you would call "Retina"
    var retinaPixelRatioThreshold = 1.5;
    // The max amount you want a non-retina image to stretch before changing it to retina
    var imageStretchRatioThreshold = 1.5;
    // The device's pixel ratio
    var dpr = (window.devicePixelRatio !== undefined) ? window.devicePixelRatio : 1;
    // Defining the boolean for what is retina
    var isRetina = dpr >= retinaPixelRatioThreshold;
    // Variable used to throttle $(window).resize()
    var windowResizeThrottle;

    // @see http://stackoverflow.com/questions/14651348/checking-if-image-does-exists-using-javascript
    function imageExists(url, callback) {
      var img = new Image();
      img.onload = function() { callback(true); };
      img.onerror = function() { callback(false); };
      img.src = url;
    }

    function loadRetinaImages() {
      $('img[data-retina-src][width]').each(function(){
        var $img = $(this);
        var actualWidth = $img.attr('width');
        var retinaSrc = $img.attr('data-retina-src');
        var maxWidthForRetinaDevice = actualWidth / retinaPixelRatioThreshold;
        var maxWidthForNonRetinaDevice = actualWidth * imageStretchRatioThreshold;

        function imageExistsCallback(fileExists) {
          // The retina exists so load the retina image
          if(fileExists) $img.attr('src', retinaSrc);
          // Remove the data-retina-src attribute so it doesn't repeat images
          $img.removeAttr('data-retina-src');
        }

        // If device is retina and the current image width is greater than the actual size / retinaPixelRatioThreshold
        // OR if device is not retina and current image width is greater than the stretching threshold we set
        // Then, switch it to retina
        if((isRetina && $img.width() >= maxWidthForRetinaDevice) || (!isRetina && $img.width() >= maxWidthForNonRetinaDevice)) {
          // Test the retina image src to see if it exists 
         ...