Our application uses a lot of configuration options. Those options need to be reflected on the client side in the form of User preferences, site wide preferences, etc.
Currently, we pass server side settings down to the client side in the form of JSON that is stored in custom attributes in the markup for a specific element (and no, our application currently doesn't worry about W3C validation). We then retrieve the data from the custom attribute, and parse it into a JSON object for use in script using jQuery.
One drawback to this is referencing attributes on elements from within event handlers. I know this is frowned upon, as it can create circular references, and subsequently memory leaks. I would much prefer to use jQuery's data function, but you can't invoke this from the server side at page render time.
What does everyone else do in this type of scenario?
JavaScript. JavaScript is a client-side script, meaning the browser processes the code instead of the web server. Client-side scripts are commonly used when we want to validate data before sending it to the web server, adjusting the interface in response to user feedback, and for implementing other advanced features.
While most JavaScript applications run on the client side, there are some server-side applications that it is useful for, such as creating web servers. With its many capabilities, it is no wonder that JavaScript is so popular.
Client-side JavaScript programs are usually event-based, which means that JavaScript event handlers are executed in response to user interactions with the browser and the document. The client-side JavaScript scripting framework is powerful enough to open substantial security holes in web browsers.
Return the server data in JSON format. You could do this through AJAX by returning a JSON header, or simple page outup and JSON.parse()
.
You can assign the JSON data directly to an element's data.
$('#elementid').data('serverdata', data);
After better understanding your situation I would suggest you use the data-
attributes for three reasons.
.data
function.customAtt="value"
to data-customAtt="value"
Here is some more information on the data attributes.
You can render in the page an inline script that defines a JS object with all the preferences. This way, your scripts have access to the data the moment the browser is done with the page load. The drawbacks:
Or you can render in the page a link to an external script that declares the preferences. This way, the preferences don't block the page rendering, and can be cached separately by the browser. Drawbacks:
Or you could directly add the data to an element using the HTML5 data attributes (thus being HTML5 conformant and jQuery.Data compatible, as it uses those as well). Drawback:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With