Embed initial data as a JSON snippet in a JavaScript widget?
I am developing a JavaScript widget. As an example, let's say the widget displays a list of posts published by a given customer.
The usual approach is something like this:
<div id="myposts-widget" data-customer-id="42">Loading...</div>
<script src="https://www.myposts.com/widget.js"></script>
First, the browser loads, parses and executes the script. Then, the script looks up the customer ID, fetches the list of posts 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="myposts-widget">Loading...</div>
<script src="https://www.myposts.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.
I had a look at numerous widgets/embeds all over the web, and it’s like everybody uses the first approach (with two roundtrips). Am I missing something? Do you have any recommandation or comment?