Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to lazily hydrate components #29

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add ability to lazily hydrate components
kaicataldo committed Sep 23, 2021
commit ff2b18daefffcbce6b4759552e84535985c4fc02
170 changes: 115 additions & 55 deletions assets/hydrated-components.js
Original file line number Diff line number Diff line change
@@ -4,6 +4,64 @@ import React from "react";
import ReactDOM from "react-dom";
import componentsLoader from "./autogenerated-components-loader";

const CAN_LAZILY_HYDRATE = "IntersectionObserver" in window;

function generateHydrationMarkersMap() {
const markerHeaderSubstring = "__ELEVENTY_REACT_HYDRATION_MARKER__:";
const nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_COMMENT,
{
acceptNode(node) {
return node.textContent.startsWith(markerHeaderSubstring)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
}
);
const markers = {};
let currentNode;

while ((currentNode = nodeIterator.nextNode())) {
let data;
try {
const rawJSON = currentNode.textContent.replace(
markerHeaderSubstring,
""
);
data = JSON.parse(rawJSON);
} catch {
console.error("Unable to parse JSON data");
}

if (!markers[data.id]) {
markers[data.id] = {};
}

markers[data.id][data.loc] = {
node: currentNode,
data,
};
}

return markers;
}

function hydrateComponent(
Component,
markerNode,
serializedProps,
componentNodes
) {
// Hydrate the Component in a separate container in case it has siblings.
const containerEl = document.createElement("div");
containerEl.append(...componentNodes);
const props = JSON.parse(serializedProps);
ReactDOM.hydrate(<Component {...props} />, containerEl);
markerNode.replaceWith(...containerEl.children);
containerEl.remove();
}

(async () => {
const componentCache = {
_cache: new Map(),
@@ -19,76 +77,78 @@ import componentsLoader from "./autogenerated-components-loader";
return component.default;
},
};

const markers = (function generateHydrationMarkersMap() {
const markerHeaderSubstring = "__ELEVENTY_REACT_HYDRATION_MARKER__:";
const nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_COMMENT,
{
acceptNode(node) {
return node.textContent.startsWith(markerHeaderSubstring)
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
},
}
);
const markers = {};
let currentNode;

while ((currentNode = nodeIterator.nextNode())) {
let data;
try {
const rawJSON = currentNode.textContent.replace(
markerHeaderSubstring,
""
);
data = JSON.parse(rawJSON);
} catch {
console.error("Unable to parse JSON data");
}

if (!markers[data.id]) {
markers[data.id] = {};
}

markers[data.id][data.loc] = {
node: currentNode,
data,
};
}

return markers;
})();
const markers = generateHydrationMarkersMap();
const lazyHydrateMap = new WeakMap();
let observer;

await Promise.all(
Object.values(markers).map(async ({ start, end }) => {
const { componentName, props: serializedProps } = start.data;
const Component = await componentCache.get(componentName);
const { componentName, props: serializedProps, lazy = true } = start.data;

const startMarkerNode = start.node;
const endMarkerNode = end.node;
const componentNodes = [];

let nodeToCheck = startMarkerNode.nextSibling;
while (nodeToCheck !== endMarkerNode) {
componentNodes.push(nodeToCheck);
nodeToCheck = nodeToCheck.nextSibling;
}
endMarkerNode.remove();

// Hydrate the Component in a separate container in case it has siblings.
const containerEl = document.createElement("div");
containerEl.append(...componentNodes);
if (CAN_LAZILY_HYDRATE && lazy) {
if (!observer) {
observer = new IntersectionObserver(
async (entries, observerInstance) => {
for (const { intersectionRatio, target } of entries) {
// Will be executed when instantiated. Guard against prematurely
// hydrating components who aren't in the viewport.
if (intersectionRatio === 0) {
continue;
}

const props = JSON.parse(serializedProps);
ReactDOM.hydrate(<Component {...props} />, containerEl);
const {
componentName,
startMarkerNode,
serializedProps,
componentNodes,
} = lazyHydrateMap.get(target);
console.log("Hydrated lazily: " + componentName);

startMarkerNode.replaceWith(...containerEl.children);
containerEl.remove();
endMarkerNode.remove();
hydrateComponent(
await componentCache.get(componentName),
startMarkerNode,
serializedProps,
componentNodes
);

observerInstance.unobserve(target);
}
}
);
}

// IntersectionObserver requires that the node being observed is an Element.
const markerEl = componentNodes.find((node) => node instanceof Element);
lazyHydrateMap.set(markerEl, {
componentName,
startMarkerNode,
serializedProps,
componentNodes,
});
observer.observe(markerEl);
return;
}

hydrateComponent(
await componentCache.get(componentName),
startMarkerNode,
serializedProps,
componentNodes
);

console.log("Hydrated normally: " + componentName);
})
);
})().catch((err) =>
console.error(
`Could not hydrate interactive components. Error: ${err.message}`
)
console.error(`Could not hydrate interactive components. Error: ${err}`)
);