Skip to content

Instantly share code, notes, and snippets.

@tjhanley
Last active August 29, 2015 14:09
Show Gist options
  • Save tjhanley/c37cfc7531a3b3e4f3e3 to your computer and use it in GitHub Desktop.
Save tjhanley/c37cfc7531a3b3e4f3e3 to your computer and use it in GitHub Desktop.
Emerson Trait for lazy loading the correct images based on media query. Follows the same image list pattern as Foundation's Interchange
/**
* Combines some functionality of Foundation.interchange & custom Lazy Loading
*
* dependencies:
* Foundation
* jquery.viewport
*
* references:
* http://foundation.zurb.com/docs/components/interchange.html
* http://foundation.zurb.com/docs/javascript-utilities.html#media-queries
*/
(function($, define) {
var trait = define('adaptive-image', {
initialize : function initialize() {
if(this.is(":in-viewport")){
this.fetch();
}
},
subscribe : {
window : {
'scroll' : function(ev) {
if(this.is(":in-viewport") && this.attr('src').length <= 0){
this.fetch();
}
}
}
}
});
trait.extend({
fetch: function(){
var image_srcs = this.data('image-srcs');
_self = this;
$.each(Foundation.libs.interchange.settings.named_queries, function(k,v){
if(matchMedia(Foundation.libs.interchange.settings.named_queries[k]).matches){
_self.imageFor(k,image_srcs);
}
});
},
imageFor: function(mediaQuery, imageList){
imageArr = imageList.split(/\],\s?\[/);
_self = this;
$.each(imageArr, function(i,v){
imgMqArr = v.replace(/(^\[|\]$)/g,'').split(',');
rx = new RegExp("(" + mediaQuery + ")");
if(imgMqArr[1].match(rx)){
_self.attr('src', imgMqArr[0]);
}
});
}
});
})(Emerson.base, Emerson.trait);
// VENDOR
//= require vendor/jquery.viewport
//= require underscore
//= require emerson
//= require foundation
// TRAITS
//= require shared/traits/adaptive_image
$(function(){ $(document).foundation();});
(function($, window) {
$(window).load(function() {
Emerson.init();
});
})($, this);
=image_tag("", data: {traits: 'adaptive-image', image_srcs:"[//bevel-assets.s3.amazonaws.com/mobile/about-razor-box.jpg, (default)], [//bevel-assets.s3.amazonaws.com/mobile/[email protected], (retina)]"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment