1/** 2* Gumby Retina 3*/ 4!function($) { 5 6 'use strict'; 7 8 function Retina($el) { 9 10 Gumby.debug('Initializing Retina', $el); 11 12 this.$el = $el; 13 this.imageSrc = this.$el.attr('src'); 14 this.retinaSrc = this.fetchRetinaImage(); 15 this.$retinaImg = $(new Image()); 16 17 var scope = this; 18 19 // image src not valid 20 if(!this.retinaSrc) { 21 return false; 22 } 23 24 // load retina image 25 this.$retinaImg.attr('src', this.retinaSrc).load(function() { 26 scope.retinaImageLoaded(); 27 }).error(function() { 28 Gumby.error('Couln\'t load retina image: '+scope.retinaSrc); 29 }); 30 } 31 32 // fetch retina src by appending '@2x' to image string before extension 33 Retina.prototype.fetchRetinaImage = function() { 34 var imgSrc = this.imageSrc, 35 index = this.imageSrc.search(/(\.|\/)(gif|jpe?g|png)$/i); 36 37 // image src is not valid 38 if(index < 0) { 39 return false; 40 } 41 42 // return retina src 43 return imgSrc.substr(0, index) + '@2x' + imgSrc.substr(index, imgSrc.length); 44 }; 45 46 // once retina image loaded swap original src 47 Retina.prototype.retinaImageLoaded = function() { 48 Gumby.debug('Swapping image for retina version', this.$el); 49 Gumby.debug('Triggering onRetina event', this.$el); 50 this.$el.attr('src', this.$retinaImg.attr('src')).trigger('gumby.onRetina'); 51 }; 52 53 // add initialisation 54 Gumby.addInitalisation('retina', function() { 55 56 // this module is for retina devices only 57 if(!window.devicePixelRatio || window.devicePixelRatio <= 1) { 58 return; 59 } 60 61 $('img[data-retina],img[gumby-retina],img[retina]').each(function() { 62 var $this = $(this); 63 // this element has already been initialized 64 if($this.data('isRetina')) { 65 return true; 66 } 67 // mark element as initialized 68 $this.data('isRetina', true); 69 new Retina($this); 70 }); 71 }); 72 73 // register UI module 74 Gumby.UIModule({ 75 module: 'retina', 76 events: ['onRetina'], 77 init: function() { 78 Gumby.initialize('retina'); 79 } 80 }); 81}(jQuery); 82