-
Notifications
You must be signed in to change notification settings - Fork 10
lazyloadBgImages.js
The lazyloadBgImages.js script lazy loads the "All topics and services" icons. By waiting until the user's viewport is about to see the icons to download the background-css, the initial page load is sped up.
This script uses Intersection Observer API to asynchronously observe changes in the intersection of the user's viewport (the root element) and the "All topics and services" icons (the target elements). It waits till the DOM is fully loaded, then uses the Intersection Observer API to observer elements with specific class names. When the elements come into view, the background images are dynamically loaded and applied.
Defining and creating the intersection observer.
let options = {
"rootMargin": "0px",
"threshold": 0.001,
};
options
- object that controls the circumstances under which the observer's callback is invoked.
NOTE: by default, or if not specified in
options
, the root element is set to the viewport
rootMargin = 0px
- specifies a 0px margin around the root element used to compute the intersection with the target element.
threshold = 0.001
- indicates that at 0.1% of the target's visibility that the observer's callback should be executed
NOTE: A threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked.
const lazyLoadingObserver = new IntersectionObserver((elements) => {
elements.forEach((element) => {
if (element.isIntersecting) {
var className, baseURL, relativePath, bg;
// get target element via data-bg attribute
className = element.target.getAttribute('data-bg');
// get window location and relative path of image
baseURL = window.location.origin;
relativePath = imageMap[className];
// build full background image URL
if (relativePath) {
bg = `url(${baseURL}${relativePath})`;
}
// Set the background image of the target element
if (bg && bg !== 'none') {
element.target.style.backgroundImage = bg;
lazyLoadingObserver.unobserve(element.target);
}
}
});
}, options);
Initialize a Instersection Observer instance with a callback function that will be executed when a tiny bit of the target element is visible. The callback function dynamically forms and sets the background-css image of the target element.
for (const imgClass in imageMap) {
if (imageMap.hasOwnProperty(imgClass)) {
var imageElement = document.getElementsByClassName(`${imgClass} lazyload`)[0];
if (imageElement) {
lazyLoadingObserver.observe(imageElement);
}
}
}
});
Iterate over each key in imageMap
to grab the first element name with the corresponding class name and the lazyload
class. Add the element to the observer if it exists.