finishLoading()

Notifies your application once Scrivito has completed loading and displaying content for the current page.

Copy
Scrivito.finishLoading().then(loadGoogleAnalytics);
function loadGoogleAnalytics() { /* GA snippet */ }

The callback passed to finishLoading().then() is executed after the content of the current page has been fully loaded and displayed.

The example above defers loading Google Analytics until loading and displaying the page has completed. This way, rendering the page is never blocked by low-priority data transfer. Other use cases are:

  • Execute code that acts on rendered content by, for example, scrolling the initial viewport to a specific element, setting an element’s style based on its current size, and the like.
  • Signal to a prerendering service that the page has been completely rendered.


Returns

A Promise. The Promise resolves after all the pieces of content the current page consists of have been loaded and rendered. The callback passed to finishLoading().then() is executed exactly once.

Notes

finishLoading should be called after your application has been mounted (i.e., after ReactDOM.render has been called).

Examples

Notify a prerender (e.g. prerender.io) that the content is complete, and the page is ready to be saved:

Copy
window.prerenderReady = false;
ReactDOM.render(<App />, document.getElementById('application');
Scrivito.finishLoading().then(() => { window.prerenderReady = true; });

Some libraries depend on resize events to calculate the correct element sizes. In the following example, the SimpleSlider component uses such a library. Therefore, it schedules resize events after Scrivito rendering is done, whenever the component is mounted or updated:

Copy
function triggerResizeAfterLoad() {
  Scrivito.finishLoading().then(() => window.dispatchEvent(new Event('resize')));
}

const SimpleSlider = Scrivito.connect(class extends React.Component {
  componentDidMount() {
    triggerResizeAfterLoad();
  }

  componentDidUpdate() {
    triggerResizeAfterLoad();
  }

  render() { return <Slider>/* ... */</Slider> }
});

The link of a search result could pass the search term as a URL parameter q. This makes it possible to move the relevant part of the page into view. After the initial page load, this example scrolls to the element that contains the search term. We're using jQuery here:

Copy
ReactDOM.render(<App />, document.getElementById('application');

query = window.location.search.match(/q=(\w+)/);
if (!query) { return; }

term = query[1];
offset = jQuery('h1,h2,h3,p').filter(`:contains(${term})`).offset();
if (!offset) { return; }

jQuery('html, body').animate({ scrollTop: offset.top }, 500);