overlookmotel / react-lazy-data

Lazy-load data with React Suspense
MIT License
8 stars 2 forks source link

Move data cache into `<script type="application/json">` tag #19

Open overlookmotel opened 4 years ago

overlookmotel commented 4 years ago

At present, data cache is written to HTML doc as

<script>
(window["__react-lazy-data.DATA_CACHE"] = window["__react-lazy-data.DATA_CACHE"] || {}).data
  = {"factoryId": {"reqId": {"data": true} } }
</script>

Performance would be better if it were instead:

<script id="__react-lazy-data.DATA_CACHE" type="application/json">
{"factoryId": {"reqId": {"data": true} } }
</script>

and then cache read with...

window["__react-lazy-data.DATA_CACHE"] = JSON.parse(
  document.getElementById('__react-lazy-data.DATA_CACHE').textContent
);

Two reasons why this is advantageous:

  1. JSON.parse() is faster as browser knows it's JSON, and not having to use full JS parser
  2. Will not be blocked by a tight Content Security Policy (see https://github.com/zeit/next.js/pull/4943)
overlookmotel commented 4 years ago

Would require removal of preloadData() (#20). No easy way I can see to await loading of a <script type="application/json"> block later in the document.