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

58 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-06-09 04:02:03 +02:00
class BodyBackground {
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
constructor() {
this._bodyBackground = document.querySelector('#bodyBackground');
this._hqBackground = document.createElement('img');
this._bodyBackgroundStyle = this._bodyBackground.style;
this._startLazyLoad();
}
2020-06-04 02:53:55 +02:00
2020-06-09 04:02:03 +02:00
_setBodyBackgrond = urlStr => {
this._bodyBackgroundStyle.background = urlStr;
this._bodyBackgroundStyle.backgroundSize = 'cover';
this._bodyBackgroundStyle.backgroundRepeat = 'no-repeat';
this._bodyBackgroundStyle.backgroundPosition = 'center';
this._bodyBackgroundStyle.backgroundAttachment = 'fixed';
}
2020-06-04 02:53:55 +02:00
2020-06-09 04:02:03 +02:00
_lazyLoadBackground = fileName => {
2020-06-04 01:31:49 +02:00
2020-06-09 04:02:03 +02:00
// Set a low quality background image
this._setBodyBackgrond(`url('assets/backgrounds/${fileName}-low.webp')`);
2020-06-04 02:53:55 +02:00
2020-06-09 04:02:03 +02:00
// Add a class to blur it
this._bodyBackground.classList.add('blurFiltered');
this._hqBackground.onload = () => {
// After downloading the HQ image, set it as bg
this._setBodyBackgrond(`url('${this._hqBackground.src}')`);
// Remove class to unblur
this._bodyBackground.classList.remove('blurFiltered');
}
// Add a delay when to fetch background
setTimeout(
() => {
this._hqBackground.src = `assets/backgrounds/${fileName}.webp`;
},
50
);
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
}