Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Ask HN: Embed initial data as a JSON snippet in a JavaScript widget?
1 point by ngrilly on March 7, 2018 | hide | past | favorite
I am developing a JavaScript widget.

The usual approach is something like this:

    <div id="my-corp-widget" data-customer-id="42">Loading...</div>
    <script src="https://www.mycorp.com/widget.js"></script>
First, the browser loads, parses and executes the script. Then, the script looks up the customer ID, fetches the data and renders the widget. It is simple and it works. But the main drawback of this approach is the latency introduced by having two roundtrips to the server: one to fetch the script, another to fetch the data.

This is the reason why I'm thinking of injecting the initial data as a JSON snippet directly in the JavaScript sent by the server, in order to improve loading time by avoiding a roundtrip to the server.

The code would look like this:

    <div id="my-corp-widget">Loading...</div>
    <script src="https://www.mycorp.com/widget.js?customer_id=42"></script>
Advantage:

- 1 roundtrip instead of 2

Drawbacks:

- The script needs to be dynamically generated server-side and cannot be statically hosted on a CDN.

- The script cannot be cached as efficiently because it differs for each customer.

Do you have any recommandation or comment?



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: