Best Way To Dynamically Configure On Page JS From the Server Side?

Is there a common strategy or practice to use to configure JS scripts that will be used to display the page from the server side? I am not referring to sending an AJAX response to an AJAX request made by a user after the page has entirely loaded. Instead the scenario I am thinking of is something like when the user has a config option in a DB that should visually change the page. JS is what causes the visual change based on several configuration options for functions.

None of these visual changes matter for security, both for a user and the site, if that matters. An example option might be putting a nav bar on the left vs putting the nav bar on the right.

I came up with 2 ways to do this but, since I am fairly new to JS, I don’t know if I am evaluating them properly or if there is a better way to do this.

1 dynamically render the JS/HTML server side with the proper configuration options. Down side: this would probably be bad for caching if a visual change is widely used on a page (such as a nav bar location)

2 place the js configuration options in the form of JSON onthe page and then have JS parse and read them. Down side: a user could potentially see the JSON options on the page, although they could be in a hidden div.

The server side language is PHP, if that matters.

Any pointers toward ideas or good practices here would be helpful!

I may be missing something in your intention, but if that decision (left Vs right) is to be made server-side, why involve javascript at all?
Just have php apply a class to the nav bar and let css do its thing.

You are right, that was a bad example. CSS would be better in the nav bar case.

My actual use case is trying to configure the options of various jquery plugins, along with some custom JS. Options will vary widely on a per-user basis.

Has anyone seen a practice of placing raw json on a page for JS to read?

I don’t see any problem with doing that. I do it myself at times. In your templates just echo out the JSON into a variable within a script tag on your page and pass it to your JS when you initialize it.

Fully client-side single page apps (SPAs) often use this technique to bootstrap the app with an initial payload of data, for performance reasons.

1 Like

Great, that was what I was looking to hear. JS is not what I regularly do so I did not want to go down the wrong road inadvertently.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.