ctrlplusb / react-async-component

Resolve components asynchronously, with support for code splitting and advanced server side rendering use cases.
MIT License
1.45k stars 62 forks source link

SSR + SEO: render on server but defer client loading #30

Open mschipperheyn opened 7 years ago

mschipperheyn commented 7 years ago

I'm trying to optimize my loading strategy. My number one concern is SEO. I want server side rendering, but I also want the end user to have a smart incremental loading experience.

I was wondering if it would be possible to have a mode that renders on the server, but defers client side loading. This way, you could have something on screen, and available to the Google bot, that wasn't interactive yet. A LoadingComponent in this scenario could be designed as a transparent overlay, to be hidden once client side loading completes.

anilanar commented 6 years ago

I think the problem is react doesn't allow you to skip rendering subtrees and no-one could come up with a hack yet that would skip checksum checking and skip subtree rendering. So if you render in server and if you don't initially serve JS for subcomponents in the client side, you cannot render your App at all. If you do, your server rendered subcomponent would be replaced with a placeholder (such as Loading component) until subcomponent.js is downloaded and executed. If you really want to do it, you cannot stick to having a single root App for your whole application. You must have multiple roots and then you can load/mount them separately.

That won't allow you to have deep incremental component loading with full SSR. However that probably doesn't make much sense anyway.

neenhouse commented 6 years ago

@mschipperheyn @anilanar

I followed this thread here and here is one possible solution implementing LoadingComponent:

class SSRAsyncLoadingComponent extends Component {
    shouldComponentUpdate() {
        return false;
    }
    getExistingHtml(selector) {
        if (typeof document === 'undefined') { 
            return null;
        }
        const node = document.querySelector(selector);
        return (node && node.innerHTML) ? node.innerHTML : `Error: Element with ${selector} not found`;
    }
    render() {
        const selector = this.props.asyncLoading;
        const html = this.getExistingHtml(selector);
        return <div dangerouslySetInnerHTML={{__html: html}} />;
    }
}

const DeferredComponent = asyncComponent({
    resolve: () => import('path/to/header' /* webpackChunkName:"deferred" */),
    LoadingComponent: SSRAsyncLoadingComponent
});

*Rendering*

<div data-async-loading="header">
  <DeferredComponent asyncLoading="[data-async-loading=header]" ... />
</div>

Downside is your are rendering 2x on the client and in dev you get a mismatch error, but you save bandwidth / parse / execute of the bundle which is very significant performance gain for our use case and worth it.