Skip to content

Instantly share code, notes, and snippets.

@conspirator
Last active August 29, 2015 14:02
Show Gist options
  • Save conspirator/243f5f4ec531f5eeefc9 to your computer and use it in GitHub Desktop.
Save conspirator/243f5f4ec531f5eeefc9 to your computer and use it in GitHub Desktop.
jQuery(function(){
if (window.matchMedia) {
if (window.matchMedia("(max-device-width: 480px)").matches) {
//
// Swaps in new mobile src for existing images
// Expects: <img class="mobile-src-overwrite-400" src="path/to/asset?parms=1" width="800">
// Returns: <img class="mobile-src-overwrite-400" src="path/to/asset-mobile?fmt=png-alpha&wid=400&qlt=95" width="400">
//
jQuery('[class*="mobile-src-overwrite-"]').each(function(){
var $el = jQuery(this),
classList = $el.attr('class').split(' '),
desiredMobileWidth = 0,
newSrc = $el.attr('src').split('?')[0];
// Hack to determine proper image width
for (var i = classList.length - 1; i >= 0; i--) {
var className = classList[i];
if (className.indexOf('mobile-src-overwrite-') > -1) {
desiredMobileWidth = className.replace('mobile-src-overwrite-', '');
}
};
// Construct new "-mobile" url with desired mobile width in query string
newSrc += "-mobile?fmt=png-alpha&wid="+ desiredMobileWidth +"&qlt=95";
// Preload new image then swap out src and set proper mobile width
jQuery('<img>', {
'src': newSrc,
'load': function(){
$el.removeAttr('height width').attr({
'src': newSrc,
'width': desiredMobileWidth
});
}
});
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment