Certainly! To optimize your code by processing elements only when they come into view, we can leverage the IntersectionObserver API. This approach avoids iterating over all elements at once and enhances performance, especially for pages with numerous elements.
Here's a refactored version of your code with the following improvements:
- Lazy Loading with IntersectionObserver: Elements are processed only when they enter the viewport.
- Generic Observer Setup: A single observer can handle different types of tracking (e.g.,
trackingParams, commentId).
- Error Handling and Logging: Enhanced error reporting with clear paths to problematic properties.
- Code Cleanup: Removed redundant functions and streamlined the logic for better readability and maintainability.
Refactored Code
import { debugErr } from "./debugLog";
/**
* Utility type to extract properties safely from elements or their polymer controllers.
*/
type ElementWithProps = Element & {
trackedParams?: string;
polymerController?: {
trackedParams?: string;
__data?: {
data?: {
commentId?: string;
};
};
};
__data?: {
data?: {
commentId?: string;
};
};
};
/**
* Creates an IntersectionObserver that triggers a callback when elements matching the selector come into view.
* @param selector - CSS selector to match elements.
* @param callback - Function to execute when an element is intersecting.
*/
export function createVisibilityObserver(
selector: string,
callback: (element: ElementWithProps) => void
): IntersectionObserver {
const observer = new IntersectionObserver((entries, obs) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const target = entry.target as ElementWithProps;
callback(target);
obs.unobserve(entry.target); // Stop observing after the element is processed
}
});
}, {
root: null, // Observe within the viewport
rootMargin: "0px",
threshold: 0.1, // Trigger when 10% of the element is visible
});
// Observe existing elements
document.querySelectorAll<Element>(selector).forEach(el => observer.observe(el));
// Optionally, observe future elements added to the DOM
const mutationObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node instanceof Element && node.matches(selector)) {
observer.observe(node);
}
});
});
});
mutationObserver.observe(document.body, { childList: true, subtree: true });
return observer;
}
/**
* Finds a single element by trackingParams when it becomes visible.
* @param trackingParams - The tracking parameter to match.
* @param selector - CSS selector to locate potential elements.
* @returns A promise that resolves with the matched element.
*/
export function waitForElementByTrackingParams<T extends Element>(
trackingParams: string,
selector: string
): Promise<T> {
return new Promise((resolve, reject) => {
const handleElement = (element: ElementWithProps) => {
const params = element.trackedParams ?? element.polymerController?.trackedParams;
if (params === trackingParams) {
resolve(element as T);
} else {
searchTrackedParamsByObject(trackingParams, element).catch(reject);
}
};
const observer = createVisibilityObserver(selector, handleElement);
// Optional timeout to prevent endless waiting
const timeout = setTimeout(() => {
observer.disconnect();
reject(new Error(`Element with trackingParams "${trackingParams}" not found within timeout.`));
}, 10000); // 10 seconds timeout
// Clear timeout upon successful resolution
handleElement.prototype.resolve = () => clearTimeout(timeout);
});
}
/**
* Finds all elements by commentId when they become visible.
* @param commentId - The comment ID to match.
* @param selector - CSS selector to locate potential elements.
* @returns A promise that resolves with an array of matched elements.
*/
export function waitForElementsByCommentId<T extends Element>(
commentId: string,
selector: string
): Promise<T[]> {
return new Promise((resolve, reject) => {
const matchedElements: T[] = [];
const handleElement = (element: ElementWithProps) => {
const data = element.__data?.data?.commentId ?? element.polymerController?.__data?.data?.commentId;
if (data === commentId) {
matchedElements.push(element as T);
// You can choose to resolve immediately or wait for more elements
// Here, we'll resolve after finding the first match
resolve(matchedElements);
} else {
searchTrackedParamsByObject(commentId, element).catch(reject);
}
};
const observer = createVisibilityObserver(selector, handleElement);
// Optional timeout to prevent endless waiting
const timeout = setTimeout(() => {
observer.disconnect();
if (matchedElements.length > 0) {
resolve(matchedElements);
} else {
reject(new Error(`Elements with commentId "${commentId}" not found within timeout.`));
}
}, 10000); // 10 seconds timeout
// Clear timeout upon successful resolution
handleElement.prototype.resolve = () => clearTimeout(timeout);
});
}
/**
* Recursively searches an element object for a specific parameter and logs the path if found.
* @param param - The parameter value to search for.
* @param elem - The element to inspect.
*/
export async function searchTrackedParamsByObject(
param: string,
elem: Element
): Promise<void> {
const elemObj = Object(elem);
const search = (obj: Record<string, any>, history: string[]): void => {
for (const key of Object.keys(obj)) {
if (typeof obj[key] === "object" && obj[key] !== null) {
try {
search(obj[key], [...history, key]);
} catch (err) {
// Propagate the error upwards
throw err;
}
} else if (obj[key] === param) {
const path = [...history, key].join(" > ");
throw debugErr(new Error(`Unknown Object format! Path: "${path}"`));
}
}
};
try {
search(elemObj, []);
} catch (err) {
// Error already logged in debugErr
return;
}
debugErr(new Error(`Parameter "${param}" not found in the element.`));
}
/**
* Interface representing a ShadyElement with potential nested properties.
*/
export interface ShadyElement extends HTMLElement {
__shady_native_children: HTMLCollectionOf<ShadyElement>;
__shady_native_innerHTML: string;
__data: {
data: {
commentId: string;
};
};
polymerController: {
__data: {
data: {
trackingParams: string;
commentId: string;
};
};
};
}
Explanation of Changes
-
IntersectionObserver Integration:
createVisibilityObserver: This function sets up an IntersectionObserver for a given selector. When elements matching the selector enter the viewport (10% visibility threshold), the provided callback is invoked, and the element is unobserved to prevent repeated triggers.
- MutationObserver: This ensures that dynamically added elements matching the selector are also observed.
-
Generic Waiting Functions:
waitForElementByTrackingParams: Returns a promise that resolves when an element with the specified trackingParams becomes visible.
waitForElementsByCommentId: Returns a promise that resolves with an array of elements matching the commentId when they become visible.
-
Error Handling:
searchTrackedParamsByObject: Recursively searches through the element's properties to find the param. If found, it logs the path; otherwise, it logs that the parameter wasn't found.
- Timeouts: Added a 10-second timeout to prevent promises from waiting indefinitely.
-
Code Optimization:
- Type Safety: Improved type definitions with
ElementWithProps to safely access properties.
- Reduced Redundancy: Combined similar functionalities into generic functions.
- Enhanced Readability: Clear function names and comments for better understanding.
Usage Example
Here's how you can use the refactored functions in your application:
// Example usage for trackingParams
waitForElementByTrackingParams<Element>('desiredTrackingParam', '.trackable-element')
.then(element => {
// Element with the specified trackingParams is now visible
console.log('Found element:', element);
})
.catch(error => {
console.error(error);
});
// Example usage for commentId
waitForElementsByCommentId<ShadyElement>('desiredCommentId', '.comment-element')
.then(elements => {
// Elements with the specified commentId are now visible
console.log('Found elements:', elements);
})
.catch(error => {
console.error(error);
});
Benefits of This Refactoring
- Performance Optimization: By observing elements as they become visible, the script avoids unnecessary processing of all elements upfront.
- Scalability: The observer pattern scales better with a growing number of elements.
- Maintainability: The code is cleaner, less redundant, and easier to manage or extend in the future.
- Enhanced User Experience: Reduces the computational load, leading to smoother interactions, especially on resource-constrained devices.
Feel free to adjust the selectors, thresholds, and timeout durations as per your application's specific requirements.