I’m working on a website wherein the “home” page for a user includes some data for use by some extensive JavaScript code. Currently the data is encoded as a JSON object in a script tag at the end of the document body and a GUI control object is instantiated just afterwards so that it has access to both the DOM and the JSON object. I like this structure because it allows the page to load quickly. It looks something like this:
<body>
<script type="text/javascript" src="mylib.js"></script>
<div>...lots of DOM and text content...</div>
<script type="text/javascript">
var userData = {...}; // Encoded by HTTP response handler.
$(document).ready(function() {
// GUI object which modifies form controls, etc.
new MyGuiObject(userData, document.form.myForm);
};
</script>
</body>
However, new functionality might require the userData object to be returned as a separate HTTP request, which means the inline form would be a duplicate (and violation of the DRY principle). It’s tempting to refactor the above code to use that AJAX request for the userData but it introduces yet another HTTP request for data we know is needed (and available) immediately.
Is it worth changing the code to use the userData retrieved from an AJAX call? If so, what is a best practice for encoding the URL from which the data is retrieved (considering that it would be better dynamically generated by the web framework)?
I wouldn’t have thought so, but this is going to be a matter of opinion and somewhat dependent on your overall environment. It’s a judgement call.
Provided you have underlying code that generates the object (whether within the initial
scriptelement or later in response to the ajax call), you’re not violating the DRY principle.If the HTML page on which that appears is completely static (and therefore cacheable), then you’d be repeating yourself as you’d have to first have the object in the HTML, then again create it with a dynamic response to an ajax request. But if the initial HTML is already dynamically-generated, then just use a central function to generate the object in both cases. (The function can generate a string in JSON format, then on the HTML page just output that with
var userData =in front of it, since JSON is a subset of JavaScript object literal format and so you can drop it into script where an object literal is valid.)DRY or not, I’d be loathe to add an avoidable HTTP request to my page load.
I’m not entirely sure what you mean by encoding the URL. If you mean the response containing the JSON, just send it back with
Content-Type: application/json. jQuery will understand that and deserialize it into an object for you before handing it to yoursuccessfunction.