the-glorious-startpage/js/body-background-set.js

75 lines
2.0 KiB
JavaScript
Raw Normal View History

class DummyBodyBackground {
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
constructor() {
this._body = document.body;
this._dummyBodyBackground = document.querySelector('#dummyBodyBackground');
this._bodyStyle = this._body.style;
this._dummyBodyBackgroundStyle = this._dummyBodyBackground.style;
this._hqBackground = document.createElement('img');
// Initialize
2020-06-09 04:02:03 +02:00
this._startLazyLoad();
}
2020-06-04 02:53:55 +02:00
_styleBodyBackgrond = (elemStyle, urlStr) => {
elemStyle.background = urlStr;
elemStyle.backgroundSize = 'cover';
elemStyle.backgroundRepeat = 'no-repeat';
elemStyle.backgroundPosition = 'center';
elemStyle.backgroundAttachment = 'fixed';
2020-06-09 04:02:03 +02:00
}
2020-06-04 02:53:55 +02:00
2020-06-09 04:02:03 +02:00
_lazyLoadBackground = fileName => {
// Add a class to blur the dummy background
this._dummyBodyBackground.classList.add('dummyBackgroundBlur');
2020-06-09 04:02:03 +02:00
// Set a low quality background image for the dummy background
this._styleBodyBackgrond(this._dummyBodyBackgroundStyle, `url('assets/backgrounds/${fileName}-low.webp')`);
// After loading/fetching the _hqBackground's background image
2020-06-09 04:02:03 +02:00
this._hqBackground.onload = () => {
// After downloading the HQ image, set it as bg of body
this._styleBodyBackgrond(this._bodyStyle, `url('${this._hqBackground.src}')`);
// Add a delay before hiding the overlay dummy background to avoid the white flicker
setTimeout (
() => {
// Hide the dummy background
this._dummyBodyBackground.classList.add('dummyBackgroundHide');
// Remove class to unblur
this._dummyBodyBackground.classList.remove('dummyBackgroundBlur');
},
2020-06-13 04:48:13 +02:00
3000
)
2020-06-09 04:02:03 +02:00
}
// Add a delay when to fetch the hq background
setTimeout (
2020-06-09 04:02:03 +02:00
() => {
this._hqBackground.src = `assets/backgrounds/${fileName}.webp`;
},
500
2020-06-09 04:02:03 +02:00
);
2020-06-04 01:31:49 +02:00
}
2020-06-09 04:02:03 +02:00
_startLazyLoad = () => {
const date = new Date();
const hour = date.getHours();
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
if (hour >= 6 && hour < 12) {
this._lazyLoadBackground('morning');
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
} else if (hour >= 12 && hour < 18 ) {
this._lazyLoadBackground('noon');
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
} else {
this._lazyLoadBackground('evening');
}
2020-06-04 01:31:49 +02:00
}
2020-06-09 04:02:03 +02:00
}