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

63 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-06-04 01:36:54 +02:00
var backgroundBody = document.getElementById('bodyBackground')
2020-06-04 01:31:49 +02:00
2020-06-04 02:53:55 +02:00
// High quality background, we'll lazy load this
var hqBackground = document.createElement("img");
2020-06-04 01:36:54 +02:00
// Style body background
2020-06-04 02:53:55 +02:00
const styleBodyBackground = (bgBodyStyle) => {
bgBodyStyle.backgroundSize = 'cover';
bgBodyStyle.backgroundRepeat = "no-repeat";
bgBodyStyle.backgroundPosition = "center";
bgBodyStyle.backgroundAttachment = "fixed";
2020-06-04 01:31:49 +02:00
}
const lazyLoadBackground = (fileName) => {
2020-06-04 02:53:55 +02:00
// Shorten backgroundBody.style or alias it
var bgBodyStyle = backgroundBody.style;
2020-06-04 01:31:49 +02:00
// Set a low quality background image
2020-06-04 02:53:55 +02:00
bgBodyStyle.background = "url('assets/backgrounds/" +
2020-06-04 01:31:49 +02:00
fileName + "-low" + ".webp')";
2020-06-04 02:53:55 +02:00
styleBodyBackground(bgBodyStyle);
// Add a class to blur it
backgroundBody.classList.add("blurFiltered");
2020-06-04 01:31:49 +02:00
2020-06-04 02:53:55 +02:00
hqBackground.onload = () => {
2020-06-04 01:31:49 +02:00
// After downloading the HQ image, set it as bg
2020-06-04 02:53:55 +02:00
backgroundBody.style.background = "url("+ hqBackground.src; + ")";
styleBodyBackground(bgBodyStyle);
// Remove class to unblur
backgroundBody.classList.remove("blurFiltered");
2020-06-04 01:31:49 +02:00
}
// Add a delay when to fetch background
setTimeout(
2020-06-04 02:53:55 +02:00
() => {
hqBackground.src = "assets/backgrounds/" +
2020-06-04 01:31:49 +02:00
fileName + ".webp";
},
50
);
}
const initLazyLoad = () => {
var date = new Date();
var hour = date.getHours();
if (hour >= 6 && hour < 12) {
lazyLoadBackground("morning");
} else if (hour >= 12 && hour < 18 ) {
lazyLoadBackground("noon");
} else {
lazyLoadBackground("evening");
}
}
2020-06-04 01:36:54 +02:00
// Initialize
2020-06-04 01:31:49 +02:00
window.onload = initLazyLoad();