-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.responsiveShopifyImg.js
75 lines (64 loc) · 2.02 KB
/
jquery.responsiveShopifyImg.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* jQuery responsiveShopifyImg
* Simple jQuery plugin for responsive image support within Shopify stores using Shopify's provided image sizes.
* http://mrpunkin.github.com/jquery.responsiveShopifyImg.js
*
* Licensed under the MIT license.
* Copyright 2015 Bryan Corey
* https://github.com/mrpunkin
*/
;(function($, window, document, undefined){
var pluginName = "responsiveShopifyImg";
$.fn[pluginName] = function(){
$.data(window, pluginName, {
elements : $(this),
sizes : {
pico : 16,
icon : 32,
thumb : 50,
small : 100,
compact : 160,
medium : 240,
large : 480,
grande : 600,
'1024x1024': 1024,
'2048x2048': 2048,
master : 2048
}
});
var resize = function(e){
var p = $.data(window, pluginName),
size;
var sizes = []
$.each(p.sizes, function(k,v){ sizes.push([k, v]) });
sizes.sort(function(a,b){ return a[1] - b[1] });
console.log(sizes);
p.elements.each(function(){
var el = this,
s = $(el).width();
if($(el).height() > s) s = $(el).height();
if(window.devicePixelRatio) s = s * window.devicePixelRatio;
$.each(sizes, function(i, a){
if(s - a[1] < 0){
size = a[0];
return false;
}
});
var sizeOpts = $.map(p.sizes, function(v,s) { return s; }).join("|"),
regex = new RegExp("_("+sizeOpts+")\."),
src = $(el).data('shopify-src').replace(regex, ".").replace(/\.(jpg|png|gif)/, "_"+size+".$1"),
loader = new Image();
loader.onload = function(){
if(el.tagName.toLowerCase() == "img"){
el.src = src;
}else{
$(el).css('background-image', 'url("'+src+'")');
}
};
loader.src = src;
});
};
$(window).on("resize."+pluginName+" orientationchange."+pluginName, resize).trigger('resize.'+pluginName);
return this;
};
}(jQuery, window, document));