gatsby-source-wordpress
Version:
Source data from WordPress in an efficient and scalable way.
53 lines (50 loc) • 2.76 kB
JavaScript
import React from "react";
import ReactDOM from "react-dom/client";
let hydrateRef;
export function onRouteUpdate() {
if (`requestIdleCallback` in window) {
if (hydrateRef) {
// @ts-ignore cancelIdleCallback is on window object
cancelIdleCallback(hydrateRef);
}
// @ts-ignore requestIdleCallback is on window object
hydrateRef = requestIdleCallback(hydrateImages);
} else {
if (hydrateRef) {
clearTimeout(hydrateRef);
}
hydrateRef = setTimeout(hydrateImages);
}
}
function hydrateImages() {
const doc = document;
const inlineWPimages = Array.from(doc.querySelectorAll(`[data-wp-inline-image]`));
if (!inlineWPimages.length) {
return;
}
import( /* webpackChunkName: "gatsby-plugin-image" */`gatsby-plugin-image`).then(mod => {
inlineWPimages.forEach(image => {
var _image$parentNode, _image$parentNode$par, _image$parentNode$par2, _image$parentNode2, _image$parentNode2$cl;
// usually this is the right element to hydrate on
const grandParentIsGatsbyImage = // @ts-ignore-next-line classList is on HTMLElement
image === null || image === void 0 ? void 0 : (_image$parentNode = image.parentNode) === null || _image$parentNode === void 0 ? void 0 : (_image$parentNode$par = _image$parentNode.parentNode) === null || _image$parentNode$par === void 0 ? void 0 : (_image$parentNode$par2 = _image$parentNode$par.classList) === null || _image$parentNode$par2 === void 0 ? void 0 : _image$parentNode$par2.contains(`gatsby-image-wrapper`);
// but sometimes this is the right element
const parentIsGatsbyImage = // @ts-ignore-next-line classList is on HTMLElement
image === null || image === void 0 ? void 0 : (_image$parentNode2 = image.parentNode) === null || _image$parentNode2 === void 0 ? void 0 : (_image$parentNode2$cl = _image$parentNode2.classList) === null || _image$parentNode2$cl === void 0 ? void 0 : _image$parentNode2$cl.contains(`gatsby-image-wrapper`);
if (!grandParentIsGatsbyImage && !parentIsGatsbyImage) {
return;
}
const gatsbyImageHydrationElement = grandParentIsGatsbyImage ? image.parentNode.parentNode : image.parentNode;
if (image.dataset && image.dataset.wpInlineImage && gatsbyImageHydrationElement) {
const hydrationData = doc.querySelector(`script[data-wp-inline-image-hydration="${image.dataset.wpInlineImage}"]`);
if (hydrationData) {
const imageProps = JSON.parse(hydrationData.innerHTML);
// @ts-ignore - TODO: Fix me
const root = ReactDOM.createRoot(gatsbyImageHydrationElement);
root.render( /*#__PURE__*/React.createElement(mod.GatsbyImage, imageProps));
}
}
});
});
}
//# sourceMappingURL=gatsby-browser.js.map