lixin-web
Version:
vue and bootstrap
71 lines (65 loc) • 2.5 kB
JavaScript
import {util} from '../vuex'
import {store} from './store'
const pixelRatio = typeof window.devicePixelRatio == 'number' && window.devicePixelRatio;
export const hasWebP = () => {
return new Promise(function (resolve, reject) {
var image = new Image();
image.onload = resolve
image.onerror = function () {
reject('Could not load image');
};
image.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
});
}
util.checkWebP = store.get('isWebP')
export const preloadImage = (filename, condition = true, { ext = 'jpg', retina = false, img = new Image, bg = null, checkWebp = () => { }, isWebP = util.checkWebP} = {}) => {
if (condition) {
if (Array.isArray(filename)) {
return Promise.all(filename.map(file => preloadImage(file, condition, { ext, retina, isWebP })))
} else {
return new Promise(function (resolve, reject) {
let path = retina && pixelRatio > 1 ? `/img/sample/${filename}_${pixelRatio}x_preload` : `/img/sample/${filename}_preload`
let url;
img.onload = () => {
if (bg) {
if (bg.nodeType == 1) bg.style.backgroundImage = `url(${url})`
if (typeof bg == 'string') document.querySelector(bg).style.backgroundImage = `url(${url})`
}
return resolve(url)
}
img.onerror = reject
const setWebp = () => {
retina && pixelRatio > 1 ?
(url = img.srcset = `${path}.webp ${pixelRatio}x`) :
(url = img.src = `${path}.webp`)
}
const setOrigin = () => {
retina && pixelRatio > 1 ?
(url = img.srcset = `${path}.${ext} ${pixelRatio}x`) :
(url = img.src = `${path}.${ext}`)
}
if (isWebP) {
return setWebp()
} else if (isWebP === false) {
return setOrigin()
}
hasWebP().then(
() => {
setWebp();
checkWebp()
},
setOrigin
)
})
}
}
}
// export const setWebPBg = (filename, condition = !isMobileScreen, element = bodyElement, ext = 'jpg') => {
// if (condition) {
// let path = `/img/sample/${filename}_preload`
// hasWebP().then(
// () => element.style.backgroundImage = `url(${path}.webp)`,
// () => element.style.backgroundImage = `url(${path}.${ext})`
// )
// }
// }