(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
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.