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

Alternative approaches to SSR preparing the documentData #42

Closed
peterbe opened this issue Jun 28, 2019 · 1 comment
Closed

Alternative approaches to SSR preparing the documentData #42

peterbe opened this issue Jun 28, 2019 · 1 comment

Comments

@peterbe
Copy link
Contributor

peterbe commented Jun 28, 2019

We're currently doing this:

<script id="documentadata" type="application/json">
{"title": "Video ...", ...
</script>

and

let documentData = null;
const documentDataElement = document.getElementById("documentdata");
if (documentDataElement) {
  documentData = JSON.parse(documentDataElement.text);
}

First of all, should we use domelement.textContent instead of domelement.text??

Another approach, which might be faster is to use:

<script id="documentadata" type="application/json">
window.DOCUMENT_DATA  = JSON.parse('{"title": "Video ...", ...   ');
</script>

In this benchmark Henrik Joretag argues that it's faster to use a script tag and call JSON.parse() in it. The blog post also mentions interesting topics around escaping the JSON string correctly.

This approach obviously is going to need to be reflected in the CSP headers. If we set our CSP headers in a Netlify config file, so it becomes real HTTP headers, then can we update the nonce in runtime with a <meta> tag?

That last point about the CSP complexity might escalate the complexity to the point where this (possible) small performance boost isn't worth it.

@peterbe
Copy link
Contributor Author

peterbe commented Jul 25, 2019

Using JSON in the rendered .html (instead of inline script tags) has the following pros and cons:

Pros

  • You can set a strict CSP for js without having to mess with dynamic nonces
  • <script type="application/json"> is definitely not render blocking

Cons

  • When the app really needs the state data, it now needs to rely on reading the DOM which can have a slight performance penalty.
  • If the state data was already parsed, by the time the React App gets going there's less work to do.

However, it's good policy that our JS should be pretty progressive and almost optional. Our SSR HTML should be near perfect and JavaScript can wait. We can set defer on our main external script tags. So, we can and should delay any JavaScript as much as possible.

Therefore, I think it's fine the way it is now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant