Created
January 21, 2014 16:34
-
-
Save ferlyz05/8543367 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The template: | |
<img class="placeholder" src="avatar-small.jpg" width="200" height="200"> | |
<img class="fullImage" src="avatar-large.jpg" width="200" height="200"> | |
The CSS: | |
.fullImage { | |
transition: opacity 0.2s linear; | |
} | |
the javascript: | |
var fullImage = $('.fullImage'), | |
placeholder = $('.placeholder'); | |
fullImage | |
.css('opacity', 0) | |
.on('load', function () { | |
this.style.opacity = 1; | |
setTimeout(placeholder.remove.bind(placeholder), 500); | |
}); | |
// a simple map object, { identifier => loaded sizes } | |
var loadedImages = {}, | |
// Let's assume a basic url structure like this: | |
// "http://somesite.com/{identifier}-{size}.jpg" | |
imageRegex = /\/(\w+)-(\w+)\.jpg$/, | |
// a list of the available sizes. | |
// format is [pixel size, filename representation] | |
sizes = [ | |
[ 20, 'tiny' ], | |
[ 40, 'small' ], | |
[100, 'medium'], | |
[200, 'large' ] | |
]; | |
// extract the identifier and size. | |
function storeInfo(url) { | |
var parts = imageRegex.exec(url), | |
id = parts[1] | |
size = parts[2], | |
index; | |
// find the index which contains this size | |
sizes.some(function (info, index) { | |
if (info[1] === size) { | |
loadedImages[id] |= 1 << index; | |
return true; | |
} | |
}); | |
} | |
// once the image has loaded, then store it into the map | |
$('.fullImage').load(function () { | |
storeInfo(this.src); | |
}); | |
asBools = { | |
a: [true, true, false, true], | |
b: [false, true, false, false], | |
// etc... | |
}; | |
asInts = { | |
a: 11, // 2^0 + 2^1 + 2^3 = 1 + 2 + 8 | |
b: 2, // 2^1 | |
// etc... | |
} | |
// find the largest image smaller than the requested one | |
function getPlaceholder(fullUrl) { | |
var parts = imageRegex.exec(fullUrl), | |
id = parts[1], | |
targetSize = parts[2], | |
targetIndex; | |
sizes.some(function (info, index) { | |
if (info[1] < targetSize) { | |
targetIndex = index; | |
return true; | |
} | |
}); | |
while (targetIndex >= 0) { | |
if (loadedImages[id] & 1 << targetIndex) { | |
return fullUrl.replace(/\w+\.jpg$/, sizes[targetIndex][1] + '.jpg'); | |
} | |
--targetIndex; | |
} | |
} | |
// and in usage: | |
var placeholderUrl = getPlaceholder(fullSizeUrl); | |
if (placeholderUrl) { | |
// there has been a smaller image loaded previously, so... | |
addTheFadeInBehaviour(); | |
} else { | |
// no smaller image has been loaded so... | |
loadFullSizeAsNormal(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment