-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (78 loc) · 2.61 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
;(function () {
var canUseWebp = (function () {
var elem = document.createElement('canvas');
if (!!(elem.getContext && elem.getContext('2d'))) {
return elem.toDataURL('image/webp').indexOf('data:image/webp') === 0;
} else {
return false;
}
})();
function getOtherParams(vals){
var otherParams = {};
for(var i = 0; i < vals.length; i++) {
var arr = vals[i].split(':');
if (arr[0] === 'webp') {
otherParams.webpSrc = arr[1];
}
if (arr[0] === 'err') {
otherParams.errSrc = arr[1];
}
}
return otherParams;
}
function update(el, option) {
var attr = option.arg || 'src',
value = option.value;
if (value.indexOf('data:image') > -1) {
el.setAttribute(attr, value);
} else {
var vals = (value || '').split(','),
imgSrc = vals.shift();
if (imgSrc) {
var otherParams = getOtherParams(vals);
var webpSrc = otherParams.webpSrc || (imgSrc + '.webp'),
imgUrl = canUseWebp ? webpSrc : imgSrc;
if (attr === 'src') {
var image = new Image();
image.onload = function () {
el.setAttribute(attr, imgUrl);
};
image.onerror = function () {
if (otherParams.errSrc) el.setAttribute(attr, otherParams.errSrc);
};
image.src = imgUrl;
} else {
el.setAttribute(attr, imgUrl);
}
}
}
}
var vueWebp = {
install: function (Vue) {
Vue.directive('webp', {
inserted: function (el, data) {
update(el, {
arg: data.arg,
value: data.value
});
},
componentUpdated: function (el, data) {
if (data.value !== data.oldValue) {
update(el, {
arg: data.arg,
value: data.value
});
}
}
})
}
}
if (typeof exports == "object") {
module.exports = vueWebp
} else if (typeof define == "function" && define.amd) {
define([], function () { return vueWebp })
} else if (window.Vue) {
window.VueWebp = vueWebp
Vue.use(vueWebp)
}
})()